1

How to set the content length of the request based on the content?

For example:

POST /Display HTTP/1.0
Content-Type: application/json
Content-Length: 125

{"QueryReq":
  {
    "Tid": "Tid-123456",
    "SessionId" : "1350711351232058820" 
  }
}

On posting this request in telnet I need to press enter many times till the content length is 125 that is empty chunks are received in the server. How can set the content length automatically based on the request content?

Dai
  • 141,631
  • 28
  • 261
  • 374
vinod
  • 8,350
  • 9
  • 32
  • 36

1 Answers1

2

Set Content-Length header

var data = querystring.stringify({
  "QueryReq": { "Tid": "Tid-123456", "SessionId" : "1350711351232058820" }
});

var options = {
    host: xxx,
    port: xxx,
    ----
    ----
    headers: {
      'Content-Length': data.length
    }
};
vinayr
  • 11,026
  • 3
  • 46
  • 42
  • 5
    please do not use data.length, I bumped to this issue and author said do not use data.length, instead, use Buffer.byteLength(data). Ref question: http://stackoverflow.com/questions/18692580/node-js-post-causes-error-socket-hang-up-code-econnreset and ref issue: https://github.com/visionmedia/express/issues/1749 – Nam Nguyen Sep 09 '13 at 07:40
  • 1
    @NamNguyen is correct, I just spent ages with this [buffer issue](http://nodejs.org/api/http.html#http_response_writehead_statuscode_reasonphrase_headers). Also, you don't even need to set the length [Sending a 'Content-length' header will disable the default chunked encoding](http://nodejs.org/api/http.html#http_http_request_options_callback) – Mark Robson Dec 23 '14 at 15:26