我在學習node.js.下面的代碼取自應該工作的一本書。它拋出http.js:704 throw new Error('Can\'t set headers after they are sent.')
如果我訪問本地主機:8080 /走狗/聊天Node.js拋出一個錯誤,說:發送後無法設置標題
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var catchPhrases = ['Why I oughta...', 'Nyuk Nyuk Nyuk!', 'Poifect!', 'Spread out!',
'Say a few syllables!', 'Soitenly!'];
app.set('view engine', 'jade');
app.set('view options', { layout: true });
app.set('views', __dirname + '/views');
app.get('/stooges/chat', function(req, res, next) {
res.render('chat');
});
io.sockets.on('connection', function(socket) {
var sendChat = function(title, text) {
socket.emit('chat', {
title: title,
contents: text
});
};
setInterval(function() {
var randomIndex = Math.floor(Math.random()*catchPhrases.length)
sendChat('Stooge', catchPhrases[randomIndex]);
}, 5000);
sendChat('Welcome to Stooge Chat', 'The Stooges are on the line');
socket.on('chat', function(data){
sendChat('You', data.text);
});
});
app.get('/?', function(req, res){
res.render('index');
});
var port = 8080;
server.listen(port);
console.log('Listening on port ' + port);
哪條線,在上面的代碼觸發錯誤?爲什麼?
UPDATE: 我註釋掉線var io = require('socket.io').listen(server);
,似乎是已導致錯誤的一個。
UPDATE: 按照要求通過robertklep,這裏的聊天模板:
extends layout
block scripts
script(type='text/javascript', src='/socket.io/socket.io.js')
script(type='text/javascript')
var socket = io.connect('http://192.168.1.34:8080');
socket.on('chat', function(data) {
document.getElementById('chat').innerHTML =
'<p><b>' + data.title + '</b>: ' + data.contents + '</p>';
});
var submitChat = function(form) {
socket.emit('chat', {text: form.chat.value});
return false;
};
block content
div#chat
form(onsubmit='return submitChat(this);')
input#chat(name='chat', type='text')
input(type='submit', value='Send Chat')
代碼看起來不錯,我不能重現該問題。確保您的Node和模塊版本(合理)是最新的(我使用Node 0.10.4,Express 3.2.0和socket.io 0.9.14)。 – robertklep 2013-04-27 06:31:43
@robertklep:我使用Node 0.10.5,Express 3.2.0和socket.io 0.9.11。在我的安裝中,socket.io怎麼老了?我正在使用Ubuntu 12.04 FYI。 – adredx 2013-04-27 08:13:38
0.9.11可能是客戶端版本。順便說一句,你能不能展示你的模板? – robertklep 2013-04-27 08:16:18