1-1 安装依赖
yarn add koa koa-router koa2-cors koa-body koa-static
yarn add mongoose
yarn add require-directory
1-2 分拆项目
//index.js
const Koa = require("koa");
const app = new Koa();
const initManage = require("./config");
initManage(app);
app.listen(4000)
// config/index.js
const requireDir = require("require-directory");
const Router = require("koa-router");
const static = require("koa-static");
const body = require("koa-body");
const cors = require("koa2-cors");
function initManage(app){
app.use(body({
// 1.解析post请求,及图片上传
multipart: true,
formidable: {
maxFileSize: 200*1024*1024,
keepExtensions: true
}
}));
//2.跨域
app.use(cors());
//3.路由自动导入
requireDir(module,`${process.cwd()}/routers`,{visit:loadRouter})
function loadRouter(obj){
if(obj instanceof Router){
app.use(obj.routes())
}
}
//4.静态资源
app.use(static(`${process.cwd()}/images`))
}
module.exports = initManage;
// routers/api/article.js
const router = require("koa-router")();
router.get("/article",async ctx=>{
ctx.body = "article"
})
module.exports = router;