How to set Content-Length when sending POST request in NodeJS?


Question

var https = require('https');  

var p = '/api/username/FA/AA?ZOHO_ACTION=EXPORT&ZOHO_OUTPUT_FORMAT=JSON&ZOHO_ERROR_FORMAT=JSON&ZOHO_API_KEY=dummy1234&ticket=dummy9876&ZOHO_API_VERSION=1.0';  

var https = require('https');  
var options = {  
  host: 'reportsapi.zoho.com',  
  port: 443,  
  path: p,  
  method: 'POST'  
};  

var req = https.request(options, function(res) {  
  console.log("statusCode: ", res.statusCode);  
  console.log("headers: ", res.headers);  
  res.on('data', function(d) {  
    process.stdout.write(d);  
  });  
});  
req.end();  

req.on('error', function(e) {  
  console.error(e);  
});  

When i run the above code i am getting below error.

error message:

statusCode:  411  
headers:  { 'content-type': 'text/html',  
  'content-length': '357',  
  connection: 'close',  
  date: 'Thu, 24 Nov 2011 19:58:51 GMT',  
  server: 'ZGS',  
  'strict-transport-security': 'max-age=604800' }  
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  


411 - Length Required  

How to fix the abobe error?
I have tried doing below

var qs =   'ZOHO_ACTION=EXPORT&ZOHO_OUTPUT_FORMAT=JSON&ZOHO_ERROR_FORMAT=JSON&ZOHO_API_KEY=dummy1234&ticket=dummy9876&ZOHO_API_VERSION=1.0';
'   
options.headers = {'Content-Length': qs.length}  

But if I try this way I am getting below error:

{ stack: [Getter/Setter],  
  arguments: undefined,  
  type: undefined,  
  message: 'socket hang up' }  

Can anybody help me on this?

Thanks
koti

PS:If I enter the whole url into browser address bar and hit enter I am getting JSON response as expected.

1
8
11/25/2011 10:21:02 AM

It turns out that the solution to the given problem, when you do want to make a POST request, is apparently to set the "headers" field of the options object to contain a 'Content-Length' field.

See code here:

How to make an HTTP POST request in node.js?

7
5/23/2017 11:54:04 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon