提问者:小点点

使用中间件验证路由器中主体参数的Express Typescript API


Im使用路由器类管理我的所有路由:

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更多的值?以及如何在路由器实例中正确使用此功能。

欢迎任何反馈


共1个答案

匿名用户

您正在调用函数,而不是返回一个函数作为中间件。

请使用:

const 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 });
    }
  });
}

export default checkBodyParameters