为什么?错误:发送后无法设置标头

时间:2015-01-12 04:30:37

标签: node.js

我一直收到此错误: 错误:发送后无法设置标头。

我已阅读其他帖子,但我不明白。我没有任何双重回调或任何东西。在我的代码中导致此错误的位置?

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (http.js:689:11)
    at ServerResponse.header (/root/node_modules/express/lib/response.js:666:10)
    at ServerResponse.send (/root/node_modules/express/lib/response.js:146:12)
    at fn (/root/node_modules/express/lib/response.js:900:10)
    at View.exports.renderFile [as engine] (/root/node_modules/jade/lib/jade.js:330:12)
    at View.render (/root/node_modules/express/lib/view.js:93:8)
    at EventEmitter.app.render (/root/node_modules/express/lib/application.js:530:10)
    at ServerResponse.res.render (/root/node_modules/express/lib/response.js:904:7)
    at Query. (/root/tutsplus/server4.js:25:7)
    at Query.emit (events.js:98:17)
var express = require('express'), app = express();
var mysql   = require('mysql');

app.get('/', function(req,res) {

    var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'fuck',
        database: 'store'
    });

    var query = connection.query('SELECT * from category');

    query.on('result', function(row) {

        var category = row.category_name;

        res.render('fuck.jade', {
            category: category
        });
    });

}); // app.get

app.listen(80, function() {

    console.log('we are logged in');
});

1 个答案:

答案 0 :(得分:2)

正如我在评论中所说,这个问题几乎总是由异步操作的不当处理引起的,这会导致响应的各个部分被无序调用。

根据使用.on()的代码示例here,您只需在获得请求时结束请求:

query.on('end', function() {
     // all rows have been received
});

我认为您可能不止一次致电res.render()因为您在收集完所有数据后在query.on('result', ...)而不是query.on('end', ....)中调用它。

您执行此操作的事实:

query.on('result', ...)

可能是导致问题的错误时间问题。


从mysql nodejs连接器文档中,这是一个例子:

var query = connection.query('SELECT * FROM posts');
query
  .on('error', function(err) {
    // Handle error, an 'end' event will be emitted after this as well
  })
  .on('fields', function(fields) {
    // the field packets for the rows to follow
  })
  .on('result', function(row) {
    // Pausing the connnection is useful if your processing involves I/O
    connection.pause();

    processRow(row, function() {
      connection.resume();
    });
  })
  .on('end', function() {
    // all rows have been received
  });