C B
C B

Reputation: 13314

Sending HTTP POST data in NodeJS http

I'm trying to send a POST request. This is not using a web form, raw it should look like this.

POST /echo HTTP/1.1
Host: dpsw.info
Connection: keep-alive
Transfer-Encoding: chunked

One
Two

Using NodeJS http, this script..

var options = {
  hostname: 'dpsw.info',
  port: 80,
  path: '/echo',
  method: 'POST'
};

var req = require('http').request(options, function(res) {
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('One\nTwo');
req.end();

However when viewing in a sniffer, the data looks like this..

POST /echo HTTP/1.1
Host: dpsw.info
Connection: keep-alive
Transfer-Encoding: chunked

7
One
Two
0

I use the Request module sometimes as well, but didn't see an easy way to put in the raw data in that - only form:{}

Upvotes: 0

Views: 4600

Answers (1)

nmaier
nmaier

Reputation: 33162

From the docs:

Sending a 'Content-length' header will disable the default chunked encoding.

Since you don't want the chunked transfer encoding apparently, because that is where those additional numbers come from, you'll have to set Content-length yourself. However, many (most) servers will understand a chunked transfer encoding just fine.

Upvotes: 2

Related Questions