12
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 .

2
  • 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. Commented Nov 10, 2015 at 18:41
  • 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 . Commented Nov 10, 2015 at 18:44

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

Tried that but "content-type": "application/x-www-form-urlencoded" is also a requirement for headers.
Then you have to change your body to be in that format, not in JSON.
Yes i guess thats the problem I dont need json but data in query string according to content type . I will try to figure out format of x-www-form . Thanks.
1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.