0

I am trying to call post data method of another application(which is running in localhost:3000) using node.js. But its returning error..

The following is the code:

var options = {
  host: 'localhost',
  path: '/v1/key/11111111',
  //since we are listening on a custom port, we need to specify it by hand
  port: '3000',
  //This is what changes the request to a POST request
  method: 'POST',  
  headers: {'Content-Type': 'application/json'}
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("hello world!");
req.end();

But i am receiving error:

{"meta":{"version":1,"status_code":400},"results":{"error":{"type":"Error","message":"invalid json"}}}

When i am trying using CURL command i am getting the desired result:

curl -X POST  localhost:3000/v1/key/12345678 --header "Content-Type:application/json"

My question is how i have to construct POST request for the above requirement.

1 Answer 1

3

You specify 'application/json' in the request options. But you provide the string "Hello world!", which is not json, and that's what the error message tells you.

Try changing the header or the content.

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

2 Comments

Thanks.I want to sent empty json {} , what i have to do.. i tried req.write({}). i am receiving error throw new TypeError('first argument must be a string or Buffer');
You need to send valid json as a string, try this: req.write("{}");

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.