[英]Node.js http - send GET data to server
How can I send data with GET method using https/http module? 如何使用https / http模块的GET方法发送数据? With POST everything works.
使用POST,一切正常。
First code ( GET ): 第一个代码 ( GET ):
var querystring = require('querystring'),
protocol = require('https');
var options = {
host: 'httpbin.org',
path: 'get',
method: 'GET',
headers: {},
port: 443
};
var data = querystring.stringify({
limit: 3
});
Object.assign(options.headers, {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Content-Length': Buffer.byteLength(data)
});
var req = protocol.request(options, response => {
response.setEncoding('utf8');
var end = '';
response.on('data', data => end += data);
response.on('end', () => console.log(end));
});
req.write(data);
req.end();
Response: 响应:
{
"args": {},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"origin": "31.0.120.218",
"url": "https://httpbin.org/get"
}
Second code ( POST , I only replaced options object): 第二个代码 ( POST ,我只替换了options对象):
var options = {
host: 'httpbin.org',
path: 'post',
method: 'POST',
headers: {},
port: 443
};
Response: 响应:
{
"args": {},
"data": "",
"files": {},
"form": {
"limit": "3"
},
"headers": {
"Connection": "close",
"Content-Length": "7",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "httpbin.org"
},
"json": null,
"origin": "31.0.120.218",
"url": "https://httpbin.org/post"
}
I will be very grateful for some help, now I don't know what I am doing wrong. 我将非常感谢您的帮助,现在我不知道自己在做什么错。
Your problem is that in a get, the query is appended to the path, as @Quy points out, get requests don't have a body. 您的问题是,在获取中,如@Quy所指出的,查询被追加到路径中,获取请求没有主体。 Without an understanding of how the server is set up, I would look at doing it like so:
在不了解服务器如何设置的情况下,我会这样看:
var data = querystring.stringify({
limit: 3
});
var options = {
host: 'httpbin.org',
path: 'get?' + data,
method: 'GET',
headers: {},
port: 443
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.