Reputation: 61
Here is my frontend JS. As a side note, FormData.append() does not work, so I have to set its properties explicitly. @data
is an object with input name: value properties.
function http(data) {
const httpData = new FormData();
for (let prop in data) {
httpData[prop] = data[prop];
}
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
const status = this.status;
const data = this.responseText;
}
};
xhttp.open('POST', '/api/login');
xhttp.setRequestHeader('Content-Type', 'x-www-form-urlencoded');
xhttp.send(httpData);
}
And on the server side
app.use(express.urlencoded({
extended: true
}));
express ready to parse form data, and in the /routes/api.js
(I am using express router)
router.post('/login', (req, res, next) => {
console.log(req.body);
res.end();
});
I got req.body
as an {}
Where did I go wrong?
Upvotes: 0
Views: 1215
Reputation: 943097
You have three problems.
append()
does work. It just doesn't store the data in a way that shows up with console.log
. Assigning arbitrary properties doesn't work.Content-Type
header. This is multipart/form-data
with a mandatory boundary
parameter that you have no way of knowing. Don't try to set the Content-Type
header manually. XMLHttpRequest
will generate it automatically from the FormData object.multipart/form-data
. The built-in one does not. The documentation for it on npm suggests 4 alternatives.Upvotes: 2