【发布时间】:2020-01-23 22:13:03
【问题描述】:
我想使用 Express-Validator 验证请求对象。假设我有两条路线,一条 GET /users/:id (fetchUserById) 和 POST /users (createUser) 路线
this.router = express.Router();
this.router.route('/').post(this.userRequestValidator.createUser, this.userController.createUser);
this.router.route('/:id').get(this.userRequestValidator.fetchUserById, this.userController.fetchUserById);
如您所见,我在调用控制器逻辑之前调用了验证中间件。首先,我创建了一个基本验证器来处理验证错误并在失败时返回 HTTP 400。
export abstract class RequestValidator {
protected validate = async (request: Request, response: Response, next: NextFunction): Promise<void> => {
const errors: Result<ValidationError> = validationResult(request);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
} else {
next();
}
};
}
我的验证器函数 userRequestValidator.createUser 和 userRequestValidator.fetchUserById 只需要扩展 RequestValidator 并实现验证
export class UserRequestValidator extends RequestValidator {
public createUser = [
body('username')
.isString()
.exists(),
body('password')
.isString()
.exists(),
this.validate,
];
public fetchUserById = [
param('id')
.isString()
.isUUID()
.exists(),
this.validate,
];
}
当我致电 GET localhost:3000/users/abc 时,我会收到此回复
{
"errors": [
{
"value": "abc",
"msg": "Invalid value",
"param": "id",
"location": "params"
}
]
}
这是我期待的回应。但是当我用一个空的身体打电话给POST localhost:3000/users 时,我得到了这个回复
{
"errors": [
{
"msg": "Invalid value",
"param": "username",
"location": "body"
},
{
"msg": "Invalid value",
"param": "username",
"location": "body"
},
{
"msg": "Invalid value",
"param": "password",
"location": "body"
},
{
"msg": "Invalid value",
"param": "password",
"location": "body"
}
]
}
有人知道我可以如何解决此问题或我的设置有什么问题吗?
【问题讨论】:
-
您使用的是哪个版本的 express-validator?
标签: javascript node.js typescript express express-validator