我对这个小程序有疑问:
var http = require("http");
var request = http.request({
hostname: "localhost",
port: 8000,
path: "/",
method: "GET"
}, function(response) {
var statusCode = response.statusCode;
var headers = response.headers;
var statusLine = "HTTP/" + response.httpVersion + " " +statusCode + " " + http.STATUS_CODES[statusCode];
console.log(statusLine);
for (header in headers) {
console.log(header + ": " + headers[header]);
}
console.log();
response.setEncoding("utf8");
response.on("data", function(data) {
process.stdout.write(data);
});
response.on("end", function() {
console.log();
});
});
控制台中的结果是这样的:
---1---
我不明白为什么会这样。
原文由 Marco Ghieri 发布,翻译遵循 CC BY-SA 4.0 许可协议
从您的代码来看,您的文件似乎包含向本地主机 (127.0.0.1:8000) 发出获取请求的代码。
问题可能是您没有在本地机器上创建监听端口 8000 的服务器。
为此,您必须在可以满足您的请求的本地主机上设置服务器。
运行 server.js :节点 server.js
运行包含发出请求的代码的文件。