I am sending a JSON object to my server using post:
const xhr = new XMLHttpRequest();
var params = {
firstname: "Joe",
lastname: "Bloggs"
};
xhr.open('post', '/api/endpoint');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
...
});
xhr.send(JSON.stringify(params));
I am using express to handle requests:
...
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
...
then at my api endpoint I am using Express Router:
const express = require('express');
const router = new express.Router();
router.post('/endpoint', (req, res) => {
console.log(req.body);
});
When I print out req.body I get the following:
{ '{"firstname":"Joe","lastname":"Bloggs"}': '' }
If I use JSON.parse(req.body) I get the following error:
TypeError: Cannot convert object to primitive value at JSON.parse ()
How can I get the contents of the payload in a format that I can work with, i.e. a json object?
You indicate that you will be sending application/x-www-form-urlencoded
here:
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
and here you send JSON:
xhr.send(JSON.stringify(params));
which is a clear violation. Make sure that you respect the format you indicated to the server when making your request:
var payload = 'firstname=' + encodeURIComponent(params.firstname) +
'&lastname=' + encodeURIComponent(params.lastname);
xhr.send(payload);
If on the other hand you would like to send JSON content then you could add the corresponding body parser on the server:
app.use(bodyParser.json({ type: 'application/json' }))
then set the proper Content-Type request header on the client:
xhr.setRequestHeader('Content-type', 'application/json');
and now you can JSON.stringify
when sending the request:
xhr.send(JSON.stringify(params));
at the api endpoint, the JSON can then be extracted from req.body
(no need to use JSON.parse
)