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

1.配置项 - 图1

1.配置项 - 图2

  1. E:\毕\mongo-sale

1.config/index.js

  1. const Router = require("koa-router");
  2. const requireDirectory = require("require-directory");
  3. const render = require('koa-art-template');
  4. const static = require('koa-static');
  5. const koaBody = require('koa-body')
  6. function initManage(app) {
  7. app.use(koaBody({
  8. // 支持文件格式
  9. multipart: true, // 支持图片上传
  10. formidable: {
  11. maxFileSize: 20*1024*1024, // 文件最大2OMB
  12. keepExtensions: true // 保留文件扩展名
  13. }
  14. }));
  15. /* 加载/routers/m1下的文件时,会触发loadRouters函数 */
  16. requireDirectory(module, `${process.cwd()}/routers`, {
  17. visit: loadRouters
  18. })
  19. render(app, {
  20. root: `${process.cwd()}/views`,
  21. extname: '.html', //后缀也可以写成.art
  22. debug: process.env.NODE_ENV !== 'production'
  23. });
  24. function loadRouters(obj) {
  25. if (obj instanceof Router) {
  26. app.use(obj.routes());
  27. }
  28. }
  29. app.use(static(`${process.cwd()}/images`));
  30. app.use(static(`${process.cwd()}/static`));
  31. }
  32. module.exports = initManage;

2.models/db.js

  1. const mongoose = require("mongoose");
  2. /* 1.连接本地数据库 */
  3. mongoose.connect('mongodb://127.0.0.1:27017/students', {
  4. useNewUrlParser: true
  5. });
  6. module.exports = mongoose;

3.models/Members.js

  1. const mongoose = require("./db");
  2. const MembersSchema = new mongoose.Schema({
  3. name:String,
  4. age:String,
  5. avatar:String,
  6. like:Boolean,
  7. friend:Boolean
  8. },{
  9. versionKey: false
  10. })
  11. const MembersModel = mongoose.model("Members",MembersSchema,"members");
  12. module.exports = MembersModel;

4.入口文件index.js

  1. const Koa = require("koa");
  2. const app = new Koa();
  3. const initManage = require("./config");
  4. initManage(app);
  5. app.listen(8080)