我正在使用快速验证来验证请求字段。除了响应错误代码之外,一切都按预期工作。
我有以下代码:
//
// ValidationLeaner.js
const Joi = require('joi');
module.exports = {
body: {
name: Joi.string().min(3).max(20).required(),
classifierId: Joi.number().integer().positive().required()
}
}
//Route.js
const { Router } = require('express')
const Validate = require('express-validation')
const ValidationLearner = require('./ValidationLeaner')
const router = Router()
router.route('/').post(Validate(ValidationLearner), ...someFunction)
module.exports = router
发送正文为 POST
请求时:{name: "Leaner01", classifierId: false}
。
我收到以下回复,该回复是正确的:
{
"status": 400,
"statusText": "Bad Request",
"errors": [
{
"field": [ "classifierId" ],
"location": "body",
"messages": [ "\"classifierId\" must be a number" ],
"types": [ "number.base" ]
}
]
}
不幸的是,响应代码是500内部服务器错误,而不是响应正文中指出的400。
我们如何使 Express-validation 发送正文中指定的相同响应代码(状态:400)?
最佳答案
您的主文件(index、app 或 server.js)中是否有错误句柄,因为在 express-validation 中文档这是必需的。
您可以将此错误处理程序添加到您的主文件(index、app 或 server.js)中(如果已经有,请对其进行编辑)并重试吗?
const Validate = require("express-validation");
app.use(function(err, req, res, next) {
// specific for validation errors
if (err instanceof Validate.ValidationError)
return res.status(err.status).json(err);
// other type of errors, it *might* also be a Runtime Error
return res.status(500).send(err.stack);
});
关于javascript - 快速验证返回错误响应错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59861381/