nodemailer 总是发送相同的响应,res.send() 不工作

nodemailer always sending the same response, res.send() not working

如果电子邮件发送失败或成功,我正在尝试发送自定义回复...

服务器

router
    .post('/send-email', function (req, res) {

        let senderEmail = req.body.email;
        let message = req.body.message;

        let transporter = nodemailer.createTransport({
            host: 'mail.domain.com',
            port: 25,
            secure: false,
            auth: {
                user: "contact@domain.com",
                pass: "password"
            },
            tls: {
                secure: false,
                ignoreTLS: true,
                rejectUnauthorized: false
            }
        });

        let mailOptions = {
            from: senderEmail,
            to: 'contact@domain.com',
            subject: `TITLE`,
            html: `
                ${message}
            `
        };

        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                res.send({ ok: false, message: "fail" })
            } else {
                res.send({ ok: true, message: "success" })
            }
        });

    });

客户端

async function sendEmail(email, message) {

    let response = fetch("/send-email", {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-type": "application/json"
        },
        body: JSON.stringify({ email: email, message: message })
    })

    let result = await response;

    console.log(result)  // Always the same response
}

但是,无论邮件发送是否失败,服务器总是发送相同的响应...

我这辈子都不知道我错过了什么?

因此,此处响应的不同部分将在响应的 body 中,您必须实际阅读 body 和 response.json() 才能获得它并且看见。有关详细信息,请参阅 MDN on Fetch

你看到的所有屏幕截图都是 headers,它们与你发送的两个不同的回复没有什么不同。

显示读取 body 并解析为 JSON 的示例:

async function sendEmail(email, message) {

    let result = await fetch("/send-email", {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-type": "application/json"
        },
        body: JSON.stringify({ email: email, message: message })
    }).then(response -> response.json());   // read the response body and parse it as JSON

    console.log(result);
    return result;
}

请注意,您还应该在此处捕获错误,无论是在调用者中还是在此函数中(我不确定哪个更适合您的情况)。