Search code examples
javascriptnode.jspostdata

Getting a 400 when using http client.request in nodejs


I'm trying to fetch some data from a server using nodejs. I would like to send a POST data. There are two things that I would like to know about.

  1. How do I send the POST data?
  2. Whatever request I make using GET or POST, I always get a 400-BadRequest error. Have been searching through to solve this the whole day. Was not able to solve.

I'm sending the POST data now like request.write(JSON.stringify({key:"value"})); .. for which I'm always getting a 400 to whatever site I try this. Even on apache running at 127.0.0.1 on a php file that accepts the POST data.


Solution

  • This question was answered in another SO thread: How to make an HTTP POST request in node.js?

    Essentially:

    use require('http');

    set 'Content-Type': 'application/x-www-form-urlencoded' in the options

    In the callback, use res.on('data', ...) to transfer the posted info.