开始使用节点,等待本地主机

我是Node.js的新手,所以我想我会检查出来,做一个你好的世界。 我的三台机器都有同样的问题,Win 8,Win 7和Mac。 首先想到这是一个防火墙问题,但我检查,并在Mac和Windows 8的机器(没有检查win7的麻烦)。 当我从terminal运行Node时,浏览器等待localhost,最终超时。 我已经呆了两天了,似乎无法通过Googlefind任何解决scheme。 我错过了什么?

这是我的代码:

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); 

你不需要等待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); 

尽pipe如果你想要一个更简单的方法来创build一个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); 

您也可以使用连接中间件。 只需像下面这样使用npm安装它:

npm install -g connect

之后,你可以做一个非常简单的应用程序,如下所示:

 var app = connect() .use(connect.logger('dev')) .use(connect.static('public')) .use(function(req, res){ res.end('hello world\n'); }) .listen(3000); 

你可以在这里获得更多关于连接的 信息 。 我告诉你使用这个,因为你得到一个非常简单的服务器,很容易扩展。 但是,如果你想做拉网站,那么我会build议使用expressjs。