如何使用 https/http 模块通过 GET 方法发送数据?使用 POST 一切正常。
第一个代码 (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();
回应:
{
"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"
}
第二个代码(POST,我只替换了选项对象):
var options = {
host: 'httpbin.org',
path: 'post',
method: 'POST',
headers: {},
port: 443
};
回应:
{
"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"
}
我将非常感谢您的帮助,现在我不知道我做错了什么。
最佳答案
您的问题是,在 get 中,查询被附加到路径中,正如 @Quy 指出的那样,get 请求没有正文。如果不了解服务器是如何设置的,我会考虑这样做:
var data = querystring.stringify({
limit: 3
});
var options = {
host: 'httpbin.org',
path: 'get?' + data,
method: 'GET',
headers: {},
port: 443
};
关于javascript - Node.js http - 将 GET 数据发送到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355057/