我是一个新手,正在学习node.js,似乎遇到了一个无法解决的错误。
这是一个非常简单的初学者代码,所以不需要太多解释,而且在本地主机上运行良好,但在生产服务器上出现问题。
App.js
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 8000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
var server = app.listen(8000);
var io = require('socket.io').listen(server);
server.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
以下是可怕的错误信息!
http.js:644
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (http.js:644:11)
at ServerResponse.res.setHeader (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/patch.js:59:22)
at next (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:153:13)
at Function.app.handle (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/proto.js:198:3)
at Server.app (/home1/artalatc/public_html/cloud1/node_modules/express/node_modules/connect/lib/connect.js:66:31)
at Manager.handleRequest (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:564:28)
at Server.<anonymous> (/home1/artalatc/public_html/cloud1/node_modules/socket.io/lib/manager.js:118:10)
at Server.EventEmitter.emit (events.js:115:20)
at HTTPParser.parser.onIncoming (http.js:1793:12)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:111:23)
问题似乎出在
var io = require('socket.io').listen(server);
这一行,注释掉该行代码可以解决错误。
var socket = io.connect('http://localhost');
在生产环境中无法工作。也许从您的index.jade文件中删除它,看看是否仍然会出现错误。在开发中,这很好用,因为您的服务器和客户端都在本地主机上。但在生产中不行。客户端和服务器是不同的。 - c0deNinjavar io = require('socket.io').listen(server);
似乎可以消除错误。 - user1574965