Node.js无法加载网页,连接超时

Node.js Unable to load the webpage The connection has timed out

本文关键字:连接 超时 网页 加载 js Node      更新时间:2023-09-26

我是node.js的初学者,我把它安装在这里:https://github.com/joyent/node/wiki/Installing-Node.js-via-package-manager

我从控制台尝试了一下,它工作了:

console.log('Hello World!');

nodejs helloConsole.js

> Hello World!

然后我试图使它在HTTP服务器,这里是代码:

var http = require("http");
http.createServer(function (request, response) {
   request.on("end", function () {
      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });
      response.end('Hello HTTP!');
   });
}).listen(8080);

我从终端运行它:

nodejs hello.js

然后我打开浏览器在http://localhost:8080/,它需要很长时间来加载,然后在chrome它给了我:

Unable to load the webpage because the server sent no data.

和firefox给我的:

The connection has timed out

您正在监听请求参数的"end"事件,但在调用最外层回调函数时,请求已经结束,因此订阅该事件为时已晚。

您可以直接从最外层的回调进行响应,这是nodejs.org中的示例代码所显示的。

您将侦听器附加到request对象,侦听end事件,在该事件被request捕获之前,您将不会看到响应。

要进行测试,您可能需要将其修改为如下示例所示:http://nodejs.org/

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World'n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

尝试以下步骤,如果您使用的是windows,它可能会对您有所帮助。

  1. 从http://nodejs.org/download/下载node.exe
  2. 放置在Hard Disk Drive中,从你想要运行的D:/nodejs/node.exe
  3. 现在把你的hello.js放在同一个directory中,它应该看起来像D:/nodejs/hello.js
  4. 现在从Command Prompt转到D:/nodejs/文件夹并运行命令node hello.js