问题
I'm trying to send a custom response if the email sending fails or succeeds...
server
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" })
}
});
});
client
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
}
But, the server always sends the same response, regardless if the email sending failed or not...
For the life of me, I can't figure out what I'm missing?
回答1:
So, the differing part of the response here will be in the body of the response and you have to actually read the body with response.json()
in order to get it and see it. See MDN on Fetch for details.
All your screen shot is looking at is headers and those don't different from the two different responses you're sending.
An example that shows reading the body and parsing as 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;
}
Note, you should also be catching errors here, either in the caller or within this function (I'm not sure which is better for your situation).
来源:https://stackoverflow.com/questions/61552971/nodemailer-always-sending-the-same-response-res-send-not-working