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

时间:2020-05-02 00:39:08

标签: express nodemailer

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

服务器

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
}

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

enter image description here

对于我的一生,我无法弄清自己的缺失吗?

1 个答案:

答案 0 :(得分:1)

因此,此处响应的不同部分将在响应的正文中,您必须实际使用response.json()读取正文以获取并查看它。有关详情,请参见MDN on Fetch

您查看的所有屏幕截图都是标题,这些标题与您要发送的两个不同的响应没有区别。

显示读取正文并以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;
}

注意,您在这里也应该在调用方或此函数中捕获错误(我不确定哪种方法更适合您的情况)。