Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node js send post request with raw request body

Tags:

post

node.js

var req ={
      "request": {
        "header": {
          "username": "name",
          "password": "password"
        },
        "body": {
        "shape":"round"    
    }
      }
    };

    request.post(
        {url:'posturl',

        body: JSON.stringify(req),
        headers: { "content-type": "application/x-www-form-urlencoded"}
        },
        function (error, response, body) {        
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );

I want to send raw request body in req variable . It is working on postman but in node js i am not able to send the raw json as request body for post request .

like image 760
Zack Sac S Avatar asked Nov 10 '15 18:11

Zack Sac S


2 Answers

You are trying to send JSON (your req variable) but you are parsing it as a String (JSON.stringify(req)). Since your route is expecting JSON, it will probably fail and return an error. Try the request below:

request.post({
    url: 'posturl',
    body: req,
    json: true
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        console.log(body)
    }
});

Instead of setting your headers, you can just add the option json: true if you are sending JSON.

like image 175
Thomas Bormans Avatar answered Nov 12 '22 18:11

Thomas Bormans


Change the Content-Type to application/json, since your body is in JSON format.

like image 2
Kelly Keller-Heikkila Avatar answered Nov 12 '22 17:11

Kelly Keller-Heikkila