javascript - 带有 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();
});
解决方案
很难完全说出这个中间件的上下文,但我的直觉是,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();
});
推荐阅读
- c++ - 名称对或元组值的别名引用
- ios - usdz 文件的 SCNSceneSource 标识符为空
- mysql - 如何获取mysql中两个表之间的比较差异列值
- python - 部分覆盖 numpy 数组不起作用
- java - 使用 Vector 在视图中画线(在 Android Studio 中)
- reactjs - 如何在 react.js 中从另一个组件调用不同组件的 ComponentDidMount()
- php - 如何通过 ajax 显示带有树枝的变量?
- python - 在 Beautifulsoup 中添加标签、文本和链接组合的简单方法?
- c++ - boost::spirit 和 strict_real_policies 无法解析太长的整数
- python - pysmt z3求解器崩溃?