首页 > 解决方案 > 带有 express 的节点执行 next() 而不运行 if 语句

问题描述

我的 express 应用中有 2 个 if 语句作为中间件。第一个没问题,但在第二个之前它执行 next() 函数而不运行第二个 if 语句。

  app.use((req: Request, res: Response, next: express.NextFunction) => {
    const email: string = req.body.email;
    const phoneNum: string = req.body.phone;
    console.log(phoneNum);
    if (phoneNum) {
        if (!phone(phoneNum).isValid) {
            res.json({
                message: "invalid phone format. Expecting format like: 8001234567",
            });
        } else {
            req.body.phone = phone(phoneNum).phoneNumber;
        }
    }
    if (email) {
        if (!EmailValidator.validate(email)) {
            res.json({
                message: "invalid email format. Expecting format like: name@domain.com",
            });
        }
    }
    next();
});

更新:我尝试了返回语句,但客户端没有收到响应。更新代码:

    app.use((req: Request, res: Response, next: express.NextFunction) => {
    const email: string = req.body.email;
    const phoneNum: string = req.body.phone;
    console.log(phoneNum);
    if (phoneNum) {
        if (!phone(phoneNum).isValid) {
            res.json({
                message: "invalid phone format. Expecting format like: 8001234567",
            });
        } else {
            req.body.phone = phone(phoneNum).phoneNumber;
            return;
        }
    } else {
        return;
    }
    if (email) {
        if (!EmailValidator.validate(email)) {
            res.json({
                message: "invalid email format. Expecting format like: name@domain.com",
            });
        } else {
            return;
        }
    } else {
        return;
    }
    next();
});

标签: javascriptnode.jstypescriptexpress

解决方案


很难完全说出这个中间件的上下文,但我的直觉是,return每当您向客户端发送响应时,您都希望这样做:

app.use((req: Request, res: Response, next: express.NextFunction) => {
  const email: string = req.body.email;
  const phoneNum: string = req.body.phone;
  console.log(phoneNum);
  if (phoneNum) {
    if (!phone(phoneNum).isValid) {
      res.json({
        message: "invalid phone format. Expecting format like: 8001234567",
      });
      return;
    } else {
      req.body.phone = phone(phoneNum).phoneNumber;
    }
  }
  if (email) {
    if (!EmailValidator.validate(email)) {
      res.json({
        message: "invalid email format. Expecting format like: name@domain.com",
      });
      return;
    }
  }
  next();
});

推荐阅读