发送后无法设置标头

时间:2013-04-14 06:28:54

标签: node.js express

我正在使用节点版本0.10.3和Express 3.1.1。

我正在尝试返回一个简单的响应,但我收到以下错误:

http.js:692
    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:692:11)

我已经阅读了很多关于它的内容,并尝试了很多解决方案,但我仍然遇到了这个错误。 我已经使用了node-inspector,我在该行之后收到了错误 -

res.render('index', { title: 'Express' });

app.js:

/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , path = require('path')
  , socketio = require('socket.io');

var app = express()
  , server = http.createServer(app)
  , io = socketio.listen(server);

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'hjs');
  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());
});

server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});


io.configure('production', function(){
  io.enable('browser client etag');
  io.set('log level', 1);
});

io.configure('development', function(){
  io.set('log level', 1);
});

io.sockets.on('connection', function(socket) {
    socket.on('event', function(event) {
        socket.join(event);
    });
});

require('./routes')(app, io);

路由/ index.js:

var utils = require('../utils')
  , config = require('../config')
  , io;

module.exports = function(app, socketio) {
  io = socketio;
  app.get('/', index);
};

var index = function(req, res){
  res.render('index', { title: 'Express' });
};

视图/ index.hjs:

<!DOCTYPE html>
<html>
  <head>
    <title>{{ title }}</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome to {{ title }}</p>
  </body>
</html>

的package.json:

{
  "name": "blabla",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "app.js"
  },
  "dependencies": {
    "express": "3.0.3",
    "hjs": "0.0.4",
    "cradle": "0.6.4",
    "twiliosig": "0.0.1",
    "socket.io": "0.9.11"
  },
  "subdomain": "blabla",
  "engines": {
    "node": "0.6.x"
  }
}

任何线索?

1 个答案:

答案 0 :(得分:1)

您的socket.io版本似乎是错误的。

使用此:

"dependencies": {
  "express": "3.0.x",
  "hjs": "0.0.4",
  "cradle": "0.6.4",
  "twiliosig": "0.0.1",
  "socket.io": "0.9.x"
}

使用socket.io@0.9.16

测试