【问题标题】:Express Typescript API Validating Body Parameters in Router using MiddlewareExpress Typescript API 使用中间件验证路由器中的正文参数
【发布时间】: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


    【解决方案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
    

    【讨论】:

    • 我不知道我的 tsconfig 是否配置错误。但是在第 1 行中,我在等号位置出现错误,说“(”是预期的。
    • @JulianOtto 我的错,再试一次:)
    • 非常感谢。我对 java/typescript 很陌生,我总是在尝试导出我的东西时遇到一些问题 :)
    • 函数返回函数一开始很棘手;)
    猜你喜欢
    • 2020-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2019-02-28
    • 2023-03-09
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多