Javascript https.get()直接与地址一起使用,但不与主机、路径等一起使用对象
我有这样一个代码:Javascript https.get()直接与地址一起使用,但不与主机、路径等一起使用对象,javascript,node.js,https,Javascript,Node.js,Https,我有这样一个代码: var options = { host: "https://basic:authentication@website.com", path: "/api/address" }; var request = https.get(options, function(response){ var str = ""; response.on('data', function
var options = {
host: "https://basic:authentication@website.com",
path: "/api/address"
};
var request = https.get(options, function(response){
var str = "";
response.on('data', function(chunk){
str+=chunk;
});
response.on('end', function(){
console.log(str);
res.json(str);
});
});
request.end();
request.on('error', function(err){
console.log(err);
});
var request = https.get("https://basic:authentication@website.com/api/address", function(response){
这给了我
{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }
我不知道出了什么问题,因为如果我将请求更改为如下所示:
var options = {
host: "https://basic:authentication@website.com",
path: "/api/address"
};
var request = https.get(options, function(response){
var str = "";
response.on('data', function(chunk){
str+=chunk;
});
response.on('end', function(){
console.log(str);
res.json(str);
});
});
request.end();
request.on('error', function(err){
console.log(err);
});
var request = https.get("https://basic:authentication@website.com/api/address", function(response){
它可以工作并从api中得到答案。问题是,如果我这样做的话,我不能在调用中输入参数。有人有提示吗?问题是您的
主机
值不正确,它实际上应该只是主机名。对于HTTP基本身份验证,可以使用auth
设置。例如:
var options = {
host: "website.com",
path: "/api/address",
auth: "basic:authentication"
};
另外,显式调用request.end()
是不必要的,因为https.get()
在内部会自动为您执行此操作
我还应该注意到,由于您似乎是在用新的外部请求响应现有请求,您可以通过简单地将外部响应管道化到现有响应来进一步简化它:
https.get(options, function(response) {
// You should probably check `response.statusCode` first ...
res.set('Content-Type', 'application/json');
response.pipe(res);
}).on('error', function(err) {
// ...
});
如果服务器不支持解析
GET
请求的主体,它将解释您看到的内容(参见)。如果需要使用GET
指定参数,是否有理由不能使用查询参数?查询参数超过30个。我宁愿不要。这将是非常混乱的。明白-尽管我不认为这是您如何使用节点的https.get()
的问题。您可以尝试使用外部客户端发出带有主体的GET
请求,以确认是否是服务器忽略了它们。