课程名称:Node.js工程师养成计划
课程章节: 第九章
课程讲师:北瑶
课程内容
在 model 里面建立一个 user.js 用于链接mongoose
module.exports = app => {
const mongoose = app.mongoose
const Schema = mongoose.Schema
const UserSchema = new Schema({
username: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true,
select:false
},
phone: {
type: String,
required: true
},
image: {
type: String,
default: null
},
cover:{
type: String,
default: null
},
channeldes:{
type: String,
default: null
},
subscribeCount:{
type:Number,
default:0
}
})
return mongoose.model('User', UserSchema)
}连接mongodb 并给 password 设置了 查询时不显示
select:false
新建 controller 文件夹
'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
async index() {
var userinfo = await this.app.model.User.find()
this.ctx.body = userinfo
}
}
module.exports = HomeController;this.app.model.User 会自动找到 app文件下得 model 下的 user.js
关于数据校验
npm i egg-validate
config 文件下 plugin。js
module.exports.validate = {
enable: true,
package: 'egg-validate',
};设置为开启状态
然后创建 middleware - error_handler.js
module.exports = () => {
return async function errorHandler(ctx, next) {
try {
await next();
} catch (err) {
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error =
status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
// 从 error 对象上读出各个属性,设置到响应中
ctx.body = { error };
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
};
};设置全局得错误处理
需要再 config.default.js 引入
config.middleware = ['errorHandler'];
const Controller = require('egg').Controller
class UserController extends Controller {
async create() {
const { ctx } = this
ctx.validate({
username: { type: 'string' },
email: { type: 'string' },
password: { type: 'string' },
})
ctx.body = 'user'
}
}
module.exports = UserController此时就能得出校验结果
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦

