我正在学习 node.js。下面的代码取自一本应该可以工作的书。http.js:704 throw new Error('Can\'t set headers after they are sent.')
如果我访问 localhost:8080/stooges/chat ,它会抛出
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);
上面代码中的哪一行触发了错误?为什么?
更新:
我注释掉了这一行var io = require('socket.io').listen(server);
,这似乎是导致错误的原因。
更新: 根据 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')