我正在学习node.js.下面的代码来自一本应该正常工作的书。如果我访问localhost:8080 / stooges / chat
,它会抛出http.js:704 throw new Error('Can\'t set headers after they are sent.')
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')
答案 0 :(得分:1)
事实证明我使用的是错误的socket.io版本。我将pakcage.json中的依赖关系从0.9.10更新到0.9.14并且它有效。谢谢你的帮助!