yarn add koa koa-router koa2-cors art-template koa-art-template koa-multer mongoose
yarn add koa-bodyparser koa-body koa-static
yarn add require-directory
E:\毕设\mongo-sale
1.config/index.js
const Router = require("koa-router");
const requireDirectory = require("require-directory");
const render = require('koa-art-template');
const static = require('koa-static');
const koaBody = require('koa-body')
function initManage(app) {
app.use(koaBody({
// 支持文件格式
multipart: true, // 支持图片上传
formidable: {
maxFileSize: 20*1024*1024, // 文件最大2OMB
keepExtensions: true // 保留文件扩展名
}
}));
/* 加载/routers/m1下的文件时,会触发loadRouters函数 */
requireDirectory(module, `${process.cwd()}/routers`, {
visit: loadRouters
})
render(app, {
root: `${process.cwd()}/views`,
extname: '.html', //后缀也可以写成.art
debug: process.env.NODE_ENV !== 'production'
});
function loadRouters(obj) {
if (obj instanceof Router) {
app.use(obj.routes());
}
}
app.use(static(`${process.cwd()}/images`));
app.use(static(`${process.cwd()}/static`));
}
module.exports = initManage;
2.models/db.js
const mongoose = require("mongoose");
/* 1.连接本地数据库 */
mongoose.connect('mongodb://127.0.0.1:27017/students', {
useNewUrlParser: true
});
module.exports = mongoose;
3.models/Members.js
const mongoose = require("./db");
const MembersSchema = new mongoose.Schema({
name:String,
age:String,
avatar:String,
like:Boolean,
friend:Boolean
},{
versionKey: false
})
const MembersModel = mongoose.model("Members",MembersSchema,"members");
module.exports = MembersModel;
4.入口文件index.js
const Koa = require("koa");
const app = new Koa();
const initManage = require("./config");
initManage(app);
app.listen(8080)