Nodemailer 错误处理 (Node.js) 未按预期工作。即使 **name 输入字段** 为空,电子邮件仍会通过

Nodemailer error handling (Node.js) doesn't work as intended. Email still goes through even though **name inputfield** is empty

在前端(React)我可以做错误处理,但是,我也想在后端(Node.js)实现错误处理。我以为我可以在 transporter.sendMail 做到这一点,但它不起作用。当名称输入字段为空 时,它仍然通过 Nodemailer 发送电子邮件。我错过了什么?

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');
const creds = require('./config');

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors());

app.post('/api/contact', (req, res) => {
    const htmlEmail = `
            Name: ${req.body.name}
            Phone: ${req.body.phone}
            Email: ${req.body.email}
        `;

    const mailOptions = {
        from: req.body.name,
        to: 'MYEMAIL',
        subject: 'example message subject',
        html: htmlEmail,
    };

    const transporter = nodemailer.createTransport({
        host: 'smtp.ethereal.email',
        port: 587,
        auth: {
            user: 'MYEMAIL',
            pass: 'MYPASSWORD',
        },
    });

    transporter.sendMail(mailOptions, (err, data) => {
        if (err || req.body.name.length === 0) {
            res.json({
                status: 'fail',
            });
            console.log('Message could not be sent.');
            return null;
        } else {
            res.json({
                status: 'success',
            });
            console.log('Message sent.');
        }
    });
});

const PORT = process.env.PORT || 3001;

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

您可以在进行任何操作之前先检查req.body。就像下面这样。

app.post('/api/contact', (req, res) => {
    if(req.body.name.trim().length === 0) {
        return res.status(400).json({error: "Name is required"});
    }
    .........