初始化
$ npm init egg --type=simple
$ npm i
目录
内置基础对象
Application(app)
module.exports = (app) => {
const { router, controller } = app;
// controller文件夹 home.js HomeController类中的index方法
router.get("/", controller.home.index);
};
它继承自 Koa.Application,在它上面我们可以挂载一些全局的方法和对象
module.exports = (app) => {
app.foo = "app-foo1";
const { router, controller } = app;
router.get("/", controller.home.index);
};
class HomeController extends Controller {
async index() {
const { ctx } = this;
ctx.body = this.app.foo;
}
}
Context
const { ctx } = this;
Request & Response
Controller
这个this就是里的ctx什么的就是来自于Controller基类;
const { ctx } = this;
Service
mvc
浏览器发送请求到 c 层处理业务,c 层将条件给 M 层,M 层操作数据库返回结果给 c 层。c 层将处理好的数据给 V 层,v 层处理好页面给 c 层,c 层返回给客户端。 c:controller m:service
Helper
config
Logger
插件
egg-mongoose
npm i egg-mongoose -s
config 文件夹
// plugin.js
module.exports.mongoose = {
//激活
enable: true,
//要激活的包
package: "egg-mongoose",
};
//config.default.js
config.mongoose = {
client: {
url: "mongodb://127.0.0.1:27017/express_video",
option: {},
plugins: [],
},
};
module.exports = (app) => {
const mongoose = app.mongoose;
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
},
password: {
type: String,
required: true,
select: false,
},
email: {
type: String,
required: true,
},
phone: {
type: String,
required: true,
},
image: {
type: String,
default: null,
},
cover: {
type: String,
default: null,
},
chaneldes: {
type: String,
default: null,
},
subscribecount: {
type: Number,
default: 0,
},
});
return mongoose.model("User", UserSchema);
};
参数校验
npm i egg-validate --save
// config/plugin.js
exports.validate = {
enable: true,
package: 'egg-validate',
};
// controller
ctx.validate({ id: 'id' });
RESTful API
token 还是 jwt
安全
加了就不会自动验证token
// config.default
config.security = {
csrf: {
enable: false,
},
};