【发布时间】:2021-06-09 13:08:44
【问题描述】:
我正在使用路由器类来管理我的所有路由:
const router = express.Router();
/**
* User Sign up Route at /api/auth/register
*/
router.post(
"/register",
checkBodyParameters(['username', 'email', 'password']),
verifyRegister.ensurePasswordStrength,
verifyRegister.checkUsernameAndEmail,
AuthController.register
);
export = router;
我想检查 x-www-form-urlencoded 正文参数。查看键是否不是应有的值,或者值是否为空。
我写了一个中间件函数来检查:
import { Request, Response } from "express";
export default function checkBodyParameters(
bodyParams: Array<string>,
req: Request,
res: Response,
next
) {
let requestBodyParams: Array<string> = [];
requestBodyParams.push(req.body.username, req.body.email, req.body.password);
requestBodyParams.forEach((requestBodyParam) => {
if (bodyParams.includes(requestBodyParam)) {
if (requestBodyParam !== "") {
next();
} else {
res.status(400).json({
message: "Paremeter cant be empty",
value: requestBodyParam,
});
}
} else {
res
.status(400)
.json({ message: "Paremeter not specified", value: requestBodyParam });
}
});
}
但它似乎不喜欢我将参数传递给中间件函数
checkBodyParameters(['username', 'email', 'password'])
我的问题是如何创建一个中间件函数来接受比 req、res 和 next 更多的值?以及如何在路由器实例中正确使用该功能。
感谢任何反馈
【问题讨论】:
标签: node.js typescript express