Reputation: 1227
Now I send data to express server as query param. But, I instead send the data to express server as payload. How do I send payload data to express server? And how do I get the payload data from express server? Can anyone clear my doubts?
Here is my code,
// http request code
var http=new XMLHttpRequest();
http.open('post','localhost:9090/putData');
http.onload=function(){
if (this.status >=200 && this.status <300){
console.log(this.response);
}
};
var payload = {
data: 'Something'
}
http.send(payload);
// server.js
app.use(bodyParser.json({limit: '50mb'}));
app.use('/putData', function(req, res){
console.log(req.body); // empty object printed
})
What's wrong in my code.
Upvotes: 1
Views: 10263
Reputation: 517
You'll need to reference 'body' from the request object. Depending on the type, you can deserialize it with a parser. I use the npm package 'body-parser' to deserialize my objects to json. Set up the body parser in the express middleware as shown below
app.use(bodyparser.json({limit: '50mb'}));
Then you can use the req.body object in your following requests`
app.get('getBody', function(req, res){
console.log(req.body);
res.status(200);
});`
Upvotes: 3