在NodeJS中发送POST请求时如何设置Content-Length? [英] How to set Content-Length when sending POST request in NodeJS?
本文介绍了在NodeJS中发送POST请求时如何设置Content-Length?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
错误信息:
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
如何修复 abobe 错误?
我试过在下面做
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' }
有人可以帮我吗?
谢谢
科蒂
PS:如果我在浏览器地址栏中输入整个 url 并按回车键,我将按预期获得 JSON 响应.
PS:If I enter the whole url into browser address bar and hit enter I am getting JSON response as expected.
推荐答案
事实证明,当您确实想要发出 POST 请求时,给定问题的解决方案显然是设置选项对象的headers"字段包含一个Content-Length"字段.
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.
在此处查看代码:
这篇关于在NodeJS中发送POST请求时如何设置Content-Length?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文