javascript - Send and Get payload in express JS - Stack Overflow

admin2025-04-19  0

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.

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.

Share Improve this question edited Jun 26, 2017 at 19:18 Vasi asked Jun 26, 2017 at 19:01 VasiVasi 1,2271 gold badge10 silver badges18 bronze badges 1
  • It's not clear what you're asking; if you're just asking how to deal with things like JSON in a POST request, pretty much any Express tutorial will cover this since it's so mon. If you're asking how to send it, it depends on how you want to send it. If it's a browser, this is also well-documented in any number of tutorials. If not, you'd have to be more specific. – Dave Newton Commented Jun 26, 2017 at 19:12
Add a ment  | 

1 Answer 1

Reset to default 3

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);
});`
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745002083a279289.html

最新回复(0)