I created a report form and I use the nodemailer library to send an email once the report is written. I used to use a tag in html that looked like this: <form action="/sendReport" method="post" >
but for reasons I won’t go into, I prefer to skip sending in js. So I tried to do a fetch but obviously it doesn’t work
Here the html :
<div>
<label for="email">E-mail address</label>
<input type="text" id="emailReport" name="email" placeholder="Enter your email address" required>
</div>
<div>
<label for="subject">Subject</label>
<input type="text" id="subjectReport" name="subject" placeholder="Enter the subject of the bug" required>
</div>
<div>
<label for="description">Description of the bug</label>
<textarea rows="8" cols="30" id="descriptionReport" name="description" placeholder="Describe the bug you encountered" required></textarea>
</div>
<div>
<button onclick="sendReport()">Send the report</button>
</div>
here the js :
function sendReport() {
// Collect report information from the DOM
const email = document.getElementById('emailReport').value;
const subject = document.getElementById('subjectReport').value;
const description = document.getElementById('descriptionReport').value;
console.log(email, subject, description);
// Send the report information via an HTTP POST request
const xhr = new XMLHttpRequest();
xhr.open('POST', '/sendReport', true);
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onload = function() {
if (xhr.status === 200) {
console.log('Report sent successfully');
//do something...
} else {
console.error('Error when sending the report');
//do something else...
}
};
xhr.onerror = function() {
console.error('Error when sending the report');
};
xhr.send(JSON.stringify({email, subject, description}));
}
and here is my fetch :
const transporter = nodemailer.createTransport({
//config stuff...
});
app.post('/sendReport', (req, res) => {
const email = req.body.email;
const subject = req.body.subject;
const description = req.body.description;
console.log(email, subject, description); //here i have undefined
const mailOptions = {
from: 'my@email',
to: 'my@email',
subject: subject,
text: description
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.log(error);
res.status(500).send('Error');
} else {
console.log(email, subject, description); //here i have undefined too
console.log('E-mail send: ' + info.response);
}
});
});