node入门,等待localhost

use*_*003 1 javascript http node.js

我是 Node.js 的新手,所以我想我会检查一下并做一个 hello world。我在我的所有三台机器(Win 8、Win 7 和 Mac)上都遇到了同样的问题。起初以为是防火墙问题,但我检查了一下,它在 Mac 和 Windows 8 机器上都关闭了(没有费心检查 win7)。当我从终端运行 Node 时,浏览器会等待 localhost,然后最终超时。我已经在这两天了,似乎无法通过谷歌找到任何解决方案。我错过了什么。?

这是我的代码:

var http = require("http");
console.log("file loaded");

http.createServer(function (request, response) {
   request.on("end", function () {
      response.writeHead(200, {
         'Content-Type': 'text/plain'
      });

      response.end('Hello HTTP!');
   });
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)

hex*_*ide 5

您不需要等待 HTTP 请求结束(除此之外,它request.on('end', ..)是无效的并且永远不会触发,这就是您超时的原因)。只需发送响应:

var http = require("http");
console.log("file loaded");

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello HTTP!');
}).listen(8080);
Run Code Online (Sandbox Code Playgroud)

尽管如果您想要一种更简单的方法来创建 HTTP 服务器,最简单的方法是使用诸如Express 之类的框架。然后你的代码看起来像这样:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.set('Content-Type', 'text/plain');
  res.send(200, 'Hello HTTP!');
});

app.listen(8080);
Run Code Online (Sandbox Code Playgroud)