Zack Sac S
Zack Sac S

Reputation: 131

node js send post request with raw request body

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 .

Upvotes: 12

Views: 32794

Answers (3)

Ram
Ram

Reputation: 35

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}

Upvotes: 1

Thomas Bormans
Thomas Bormans

Reputation: 5354

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.

Upvotes: 15

Sanna Keller-Heikkila
Sanna Keller-Heikkila

Reputation: 2594

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

Upvotes: 2

Related Questions