req.body.message is returning undefined when printing. Form is trying to make a post request.
//Form
<form id="messagesubmission"method="post" action="/postmessage">
<label for="message">message:</label>
<input type="text" name="message" /><br />
<input type="submit"/>
</form>
//Javascript code to intercept data
document.getElementById('messagesubmission').addEventListener('submit', function (event) {
event.preventDefault(); // Prevent the default form submission
console.log("hit");
// Get the form data
var MessageData = new FormData(this);
// Send the form data to the server using Fetch API
fetch('/postmessage', {
method: 'POST',
body: MessageData
})
.then(function (data) {
// Update the result container with the received data
console.log(data);
})
.catch(function (error) {
console.error('Error:', error);
});
});
//Express Data
app.post("/postmessage", (req, res) => {
const MessageData = storedUsername + " - " + req.body.message + "\n";
console.log(MessageData);
res.setHeader('Content-Type', 'application/json');
fs.appendFileSync('messagelist.txt', MessageData, { flag: 'a' });
res.send(JSON.stringify({ variable: MessageData}));
});
I did some basic trouble shooting and console logging. But it keeps returning undefined