I am currently working with an express server that is serving as an API. The main.ts file, where the server is set up, looks like this:
const app = express();
app.use(bodyParser.json({ type: "application/json" }));
app.use(bodyParser.text({ type: "text/plain" }));
app.use('/', routes);
app.listen(8080, () => {});
The routes object contains a GET definition as follows:
routes.get('/myObject', (request: Request, response: Response) => {
console.log(request.body); // Output : {}
});
Recently, I encountered an issue where the request body sent from another server is not being parsed correctly.
Here is the XHR request being sent from the second server:
const request: XMLHttpRequest = new XMLHttpRequest();
request.open("GET", "http://localhost:8080/myObject");
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader("Content-Type", "text/plain");
request.setRequestHeader('Access-Control-Allow-Origin', '*');
request.onload = () => {
console.log(request.status);
};
request.onerror = (err) => {
console.log(request.status);
}
request.send(JSON.stringify({ "key": "value" }));
However, when I view the data on my express server, it only shows an empty object {} instead of { "key": "value" }. Any insights on what might be causing this issue?
Additionally, if the data appears in the format "{\"key\":\"value\"}"
on the express server, is there a way to implicitly convert it into a JSON object for the request.body?