Node.js简单服务器请求结束事件问题

4
我是一个新手,正在学习node.js。尝试让控制台在请求结束时打印内容。我尝试访问localhost:8080和localhost:8080/,但终端没有任何输出。有什么想法吗?我这样做是因为当我运行此示例时,在http://tutorialzine.com/2012/08/nodejs-drawing-game/上运行演示时,终端显示套接字已启动但未呈现index.html页。所以我无法弄清楚为什么这段代码用于为他人提供静态文件无法正常工作。
var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
// var file = new(static.Server)('./');

require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        console.log("ended");
    });
}).listen(8080);

注意:该教程是针对 Express 2.x 编写的,在该版本中 apphttp.Server 的一个实例。但在 Express 3.x 中,app 变成了一个 function,因此您不能简单地对其进行 listen() 操作。请查看 2.x 到 3.x 迁移指南,特别是 Socket.IO 兼容性 - Jonathan Lonowski
2个回答

7

看起来你正在使用Node.js 0.10.x版本,在新版本中,你需要恢复可读流以使它们触发事件:

require('http').createServer(function (request, response) {
    var body = '';
    request.setEncoding('utf8');
    request.on('readable', function () {
        body+= this.read();
    }
    request.on('end', function () {
        console.log('ended');
        console.log('Body: ' + body);
    });
    request.resume();
}).listen(8080);

2
这对我很有帮助,我的系统升级到了最新的node.js版本,突然间我的node.js应用程序出现了故障。 :/ - Nick Jennings
@NickJennings,同时需要监听“readable”事件以读取添加到答案中的数据。 - micnic

0

你应该在请求处理程序中调用 node-static serve,这样你就可以获取 index.html

var static = require('node-static');
var fileServer = new static.Server('./');

require('http').createServer(function (request, response) {
    fileServer.serve(request, response);    //add this line 
    request.addListener('end', function () {
        console.log("ended");
    });
}).listen(8080);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接