1.0.1 • Published 2 years ago
@comely-fox/express-joi v1.0.1
用于验证 params、body、query 的客户端请求字段
安装
npm i @comely-fox/express-joi
1. 导入 joi @fox/express-joi
const Joi = require('joi')
const expressJoi = require('@fox/express-joi)
2. 定义 schema 规则
const schemas = {
params:{
username: joi.string().min(2).max(12).alphanum().required()
password: joi.string().pattern(/^[a-zA-Z0-9_]{6,16}$/).required()
}
}
joi 规则查看:joi
3. 在路由中使用 express-joi 中间件
app.get('/test', expressJoi(schemas), function(req,res){ // ... })
4. 定义一个错误处理中间件,用于捕获验证失败后的错误
app.use(function(err, req, res, next) {
if(err instanceOf Joi.ValidationError){
res.send({
status: 400,
statusText: err.message
})
}
// 其他未知错误
res.send({
status: 500,
statusText: '未知错误'
})
})
许可
ISC