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

问题描述 投票:0回答:1

我试图发送一个自定义的响应,如果电子邮件发送失败或成功... ...

服务器

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: "[email protected]",
                pass: "password"
            },
            tls: {
                secure: false,
                ignoreTLS: true,
                rejectUnauthorized: false
            }
        });

        let mailOptions = {
            from: senderEmail,
            to: '[email protected]',
            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

对于我来说,我不知道我错过了什么?

express nodemailer
1个回答
1
投票

所以,这里响应的不同部分将在响应的body中,你必须实际读取body与 response.json() 为了得到它,看到它。 见 MDN在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;
}

注意,你也应该在这里捕捉错误,无论是在调用者还是在这个函数中(我不知道哪种情况更适合你)。

© www.soinside.com 2019 - 2024. All rights reserved.