11
votes
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 .

3
What is the error? Could your "content-type": "application/x-www-form-urlencoded" be incorrect, since you're sending JSON? It should be application/json. - Kelly Keller-Heikkila
POST /HTTP/JSON/Prices/GetPriceSheet.aspx HTTP/1.1 Host: host.com Content-Type: application/x-www-form-urlencoded Cache-Control: no-cache { "request": { "header": { "username": "name", "password": "pw" }, "body": { "shape":"round" } } } This is request preview that is working on postman . So i need x-www-form-urlencoded in header but also send raw json data. The error i am getting is wrong format from rest service . - Zack Sac S

3 Answers

14
votes

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.

2
votes

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

1
votes

Adding the 'Content-Length' in the header for the string that is added in the body , will resolve this issue. It worked for me.

headers:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8",'Content-Length': req.length}