node.js在发送到客户端错误后无法呈现标头

时间:2012-08-20 08:19:38

标签: javascript node.js express

使用node.js,这个错误让我感到烦恼,我想这里的表达方式有问题:var app = express(); http.createServer(app) ??有什么建议吗?

Listening to port 8000
Request / from 127.0.0.1 to localhost:8000

http.js:686
throw new Error('Can\'t render headers after they are sent to the client.'
      ^
Error: Can't render headers after they are sent to the client.

代码在这里:

var sys = require('sys'), 
http = require('http');

var express = require('express'),
    routes = require('./routes');

var app = express();
var _self = this;


var _routes = {
    '/' : function(request, response) {
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('hello world\n');
        response.end();
    },

    '/is_up' : function(request, response) {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.write('ok');
        response.end();
    },
};

var _requestHandler = function(request, response) {
    console.log('Request '+request.url+' from '+request.connection.remoteAddress+' to '+request.headers.host);
    if(_routes[request.url] === undefined) {
        response.writeHead(404, {'Content-Type': 'text/plain'});
        response.write('not found\n');
        //response.end();
    } else {
        _routes[request.url].call(this, request, response);
    }
};

var _server = module.exports = http.createServer(app).
                    addListener('request', _requestHandler)
                    .listen(8000);
    console.log('Listening to port ' + "8000");

1 个答案:

答案 0 :(得分:0)

我认为问题是由于您创建服务器的方式。看起来你有两个处理程序,一个与另一个冲突。

在您的代码中,您将Express应用程序传递给它而不是您的请求处理程序,然后在您的请求处理程序中添加一个侦听器。

将其更改为以下内容:

var _server = http.createServer(_requestHandler); 
//_server.addListener('request', _requestHandler);
_server.listen(8000);
console.log('Listening to port ' + "8000");