'Receiving HTTP POST request sent by frontend JS using router in Express.js
I am building a web application using the Express framework. I'm trying to send the username of an account (which is stored in a cookie) to the backend. This is the code in the frontend JS that sends the HTTP Post request:
var httpRequest = new XMLHttpRequest();
httpRequest.open('POST', '/loggedInAutoSubmitForm', true);
httpRequest.setRequestHeader("Content-type","application/application/json");
httpRequest.send(JSON.stringify(content));
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
var json = httpRequest.responseText;
console.log(json);
}
else {
console.log("some error happened");
}
};
content is defined and this is what I get in Chrome's console when I log content:
{"username":"testUser1"}
The content of this request is correct, but I'm not receiving it with the router in index.js. This is the backend code:
var express = require('express');
const router = express.Router();
router.post('/loggedInAutoSubmitForm', function(req, res) {
console.log(req.body);
// find user and render logged in page
});
I haven't implemented the code yet, but the problem is that I'm getting an empty request body. This is what happens in my console when I log req.body:
{}
Also, I get nothing logged in Chrome's console after the request has been sent, so I'm thinking maybe the request didn't end?
I'm fairly new to web development and I'm not sure if this is the correct way to send a Post request from the frontend. If it is, I have no idea what is wrong with this code. I have searched online but it seems that this is the proper way to receive the Post request using router. Is there any way to make it work? Any help is appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
