I'mt trying to send formData from my web app to the Express backend and send email with nodemailer as well. Mail transport works fine, except the req.body is getting empty, and the mail goes with a lot of "undefiend" fields as there must be data from the req.body.
Client side code:
async function formSend(e) {
e.preventDefault();
let formData = new FormData(form);
try {
const res = await fetch('/myendpoint', {
method: 'Post',
body: formData,
Headers: {
'Content-type': 'application/json'
}
});
if (res.ok) {
const result = await res.json();
}
catch (error) {
alert('error')
}
}
};
Backend: Route:
router.post('/', (req, res) => {
console.log(req.body);
const { value1, value2, value3, value4, value5, value6, value7, value8} = req.body;
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${name}</li>
<li>Email: ${email}</li>
<li>Phone: ${phone}</li>
<li>Category: ${category}</li>
<li>status: ${status}</li>
<li>Date: ${date}</li>
<li>witness: ${witness}</li>
</ul>
<h3>Message</h3>
<p>${message}</p>
`;
const transporter = nodemailer.createTransport({
host: 'my mail server',
port: 465,
auth: {
user: 'my mail',
pass: 'my pass'
}
});
const mailOptions = {
from: req.body.email,
to: 'my mail',
subject: `Message from ${req.body.email}`,
text: 'some title',
html: output
};
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
console.log(err);
res.send('error');
} else {
console.log('Email sent' + info.response);
res.status(200).json({ message: 'Email was sent' });
}
});
});
module.exports = router;
Server.js:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
app.use('/api/contact', require('./routes/contact'));
The console.log of req.body and mail sent function
{}
Email sent250 OK id=1mopNr-006l01-Lh
While i'm trying to console.log formData values, it shows fine, i can see, that it is not empty, but after sending it to backend, it dissapears. May be there is a mistake with promises and async/await, can't realy understand it.