简体   繁体   中英

request node.js module can't send a simple POST

I send it like so :

var url     = "http://localhost:9001/v1/sanger/auth/facebook/callback",
    options = {body: JSON.stringify(params), 'Content-type': 'application/json'};

    request.post(url, options, function (error, response, body) {
      ... callbacks ... 
    });

I am not getting the params in the route (tried body , params and query )

When I use postman ( http://cl.ly/image/473e2m173M2v ) I get it in the req.body

A better way to do this (I'm assuming you've initialized your params variable somewhere else):

request = require('request');

var options = {
  url: "http://localhost:9001/v1/sanger/auth/facebook/callback",
  method: 'POST',
  body: params,
  json: true
};

request(options, function (error, response, body) {
  ... callbacks ... 
});

You're not able to get the body because when you call JSON.stringify(params) , you're converting params to a string and you don't have a json object anymore. If you send the information as plain/text but tell the request that you want json , your express app cannot verify the content-type , as could check with:

request.get('Content-Type'); // returns undefined

Since you want a json object, you shouldn't do this. Just pass the json object, like in the example above.

Then, in your route code, you can do both req.body or req.param('a_param') (for a especific key of your json ) to get those values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM