joi验证报错UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
(node:2072) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (internal/errors.js:322:7)
at ServerResponse.setHeader (_http_outgoing.js:561:11)
at ServerResponse.header (E:\代码练习\node\day-07\blogs\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (E:\代码练习\node\day-07\blogs\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (E:\代码练习\node\day-07\blogs\node_modules\express\lib\response.js:267:15)
at ServerResponse.send (E:\代码练习\node\day-07\blogs\node_modules\express\lib\response.js:158:21)
at module.exports (E:\代码练习\node\day-07\blogs\route\admin\user-edit-fn.js:17:9)
at Layer.handle [as handle_request] (E:\代码练习\node\day-07\blogs\node_modules\express\lib\router\layer.js:95:5)
at next (E:\代码练习\node\day-07\blogs\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\代码练习\node\day-07\blogs\node_modules\express\lib\router\route.js:112:3)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2072) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
原因:joi代码更新,旧版本语法导致报错
解决方法及代码
//引入joi模块
const Joi = require('joi')
module.exports = async(req, res) => {
//定义对象的验证规则
const schema = Joi.object({
username: Joi.string().min(2).max(10).required().error(new Error('用户名不符合规则')),
email: Joi.string().email().required().error(new Error('邮箱格式不符合要求')),
password: Joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).required().error(new Error('密码不符合规则')),
role: Joi.string().valid('normal', 'admin').required().error(new Error('角色值不符合规则')),
state: Joi.number().valid(0, 1).required().error(new Error('状态值不符合规则'))
})
//用try{}catch(){}语句来捕获异步函数的异常
try {
//实施验证
await schema.validateAsync(req.body)
} catch (e) {
//验证没有通过
//e.message
//重定向回用户添加页面
res.redirect(`/admin/user-edit?${e.message}`)
}
}
浙公网安备 33010602011771号