I'm currently diving into the world of XMLHttpRequests. My goal is to send some input data to the server, but when it reaches its destination, the Object appears empty as if it were {}. I've noticed that by commenting out the setRequestHeader section, the object gets printed correctly, yet I encounter an error stating that it should be open in the browser. However, placing it after the open() statement causes it to malfunction again and the object arrives empty. I've even attempted JSON.stringfy on the variable before sending it, but with no success.
//server.js
const express = require('express');
const app = express();
const cors =require('cors')
app.use(cors())
app.use(express.urlencoded({extended:true}))
app.post('/phrases', function(req, res) {
console.log(req.body);
const phrase = new phrase(req.body);
// console.log(phrase);
})
app.listen(3000, () => console.log('listening on 3000...'));
//script.js
var form = document.getElementsByTagName('form')[0];
const xhr = new XMLHttpRequest();
// xhr.setRequestHeader('Content-Type', 'application/json');
form.onsubmit = (e) => {
e.preventDefault();
const thisName = form.elements[0].name;
const thisValue = form.elements[0].value;
const phrase = {[thisName]:thisValue};
console.log(phrase)
xhr.open('POST', 'http://localhost:3000/phrases');
xhr.send(phrase);
};
<!-- index.html -->
<form action = "http://localhost:3000/phrases" method="post">
<label for="favoritephrase"> What's your favorite phrase?
<input id= 'phrase' type="text" name="favoritephrase">
<button id= 'send-phrase' type="submit">Send</button>
</form>