1-1 安装依赖

  1. yarn add koa koa-router koa2-cors koa-body koa-static
  2. yarn add mongoose
  3. yarn add require-directory

1-2 分拆项目

1、搭建后台服务 - 图1

  1. //index.js
  2. const Koa = require("koa");
  3. const app = new Koa();
  4. const initManage = require("./config");
  5. initManage(app);
  6. app.listen(4000)
  1. // config/index.js
  2. const requireDir = require("require-directory");
  3. const Router = require("koa-router");
  4. const static = require("koa-static");
  5. const body = require("koa-body");
  6. const cors = require("koa2-cors");
  7. function initManage(app){
  8. app.use(body({
  9. // 1.解析post请求,及图片上传
  10. multipart: true,
  11. formidable: {
  12. maxFileSize: 200*1024*1024,
  13. keepExtensions: true
  14. }
  15. }));
  16. //2.跨域
  17. app.use(cors());
  18. //3.路由自动导入
  19. requireDir(module,`${process.cwd()}/routers`,{visit:loadRouter})
  20. function loadRouter(obj){
  21. if(obj instanceof Router){
  22. app.use(obj.routes())
  23. }
  24. }
  25. //4.静态资源
  26. app.use(static(`${process.cwd()}/images`))
  27. }
  28. module.exports = initManage;
  1. // routers/api/article.js
  2. const router = require("koa-router")();
  3. router.get("/article",async ctx=>{
  4. ctx.body = "article"
  5. })
  6. module.exports = router;