I have 2 if statements as middleware in my express app. The first one no problem, but before the second one it performs the next() function without running the second if statement.
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();
});
UPDATE: I tried return statements but the client doesn't receive a response. Updated code:
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();
});
It's hard to fully tell the context of this middleware, but my instinct is that you want to return whenever you're sending a response to the client:
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();
});