Node.js http.request 选项主机名参数的正确格式是什么?
What is correct format of Node.js http.request options hostname parameter?
我正在尝试向 Instagram API 发出请求,我很难理解为什么 http.request 主机名参数来自选项。
然而这是我的代码:
const http = require("http");
const https = require("https");
function requestInstagramData(){
var options = {
protocol: "https:",
hostname: "https://api.instagram.com",
path: "/v1/tags/fashion?access_token=3681332213.81b69f2.88020902f003411196c3f4423912f547",
method: "GET"
};
var instaRequest = https.request(options);
instaRequest.on("response", function(res){
res.on("data", function(data){
console.log("data has arrived");
});
console.log("response");
console.log(res.statusCode);
console.log(res.statusMessage);
});
instaRequest.end();
}
requestInstagramData();
此代码不起作用,但如果我将选项对象中的主机名更改为
hostname: "api.instagram.com"
正在运行。
为什么?
正如您在尝试 "api.instagram.com" 时已经发现的那样,hostname 属性 仅用于指定主机,主机名根据定义不包括一个协议。该协议进入 协议 属性,就像您已经完成的那样。
http.request 是一个与任何其他函数一样的函数。要正确使用它,您需要知道它可以接受什么输入,为此我们通常会查看文档。
http.request (link) says the input, the argument, must be an object consisting of protocol, hostname, path and etc. These are all the standard components of http url scheme. You can check this article (link) 的文档,非常清楚地解释了这些组件的命名方式。
牢记这两点。它不适用于 "http://",因为这是协议,不应包含在主机名中。
我正在尝试向 Instagram API 发出请求,我很难理解为什么 http.request 主机名参数来自选项。
然而这是我的代码:
const http = require("http");
const https = require("https");
function requestInstagramData(){
var options = {
protocol: "https:",
hostname: "https://api.instagram.com",
path: "/v1/tags/fashion?access_token=3681332213.81b69f2.88020902f003411196c3f4423912f547",
method: "GET"
};
var instaRequest = https.request(options);
instaRequest.on("response", function(res){
res.on("data", function(data){
console.log("data has arrived");
});
console.log("response");
console.log(res.statusCode);
console.log(res.statusMessage);
});
instaRequest.end();
}
requestInstagramData();
此代码不起作用,但如果我将选项对象中的主机名更改为
hostname: "api.instagram.com"
正在运行。
为什么?
正如您在尝试 "api.instagram.com" 时已经发现的那样,hostname 属性 仅用于指定主机,主机名根据定义不包括一个协议。该协议进入 协议 属性,就像您已经完成的那样。
http.request 是一个与任何其他函数一样的函数。要正确使用它,您需要知道它可以接受什么输入,为此我们通常会查看文档。
http.request (link) says the input, the argument, must be an object consisting of protocol, hostname, path and etc. These are all the standard components of http url scheme. You can check this article (link) 的文档,非常清楚地解释了这些组件的命名方式。
牢记这两点。它不适用于 "http://",因为这是协议,不应包含在主机名中。