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

后端 未结 4 727
甜味超标
甜味超标 2021-02-08 13:17
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&         


        
相关标签:
4条回答
  • 2021-02-08 14:00

    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?

    0 讨论(0)
  • 2021-02-08 14:01

    i think you're missing two things. Assuming p is both your endpoint and your url-encoded payload.

    You could split your p variable into the both api path, and the post_data payload you need to write before ending the request.

    var p = '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: '/api/username/FA/AA',  
      method: 'POST',
      headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Content-Length': Buffer.byteLength(p)
      } 
    }
    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.write(p);  
    req.end();  
    

    Hope it helps!!

    0 讨论(0)
  • 2021-02-08 14:04

    I am able to solve this problem by changing the method from POST to GET

    Thanks koti

    0 讨论(0)
  • 2021-02-08 14:16
    var server = http.createServer();
    server.on('request', function(req, res) {
    
        req.on('data',function(data){
    
            res.writeHead(200, {'Content-Type': 'text/plain','Content-Length':data.toString().length+''});
            res.write(data.toString());
            res.end();
        });  
    
    });
    
    0 讨论(0)
提交回复
热议问题