2015-01-12 42 views
0

我不斷收到此錯誤:錯誤:發送後無法設置標題。爲什麼?錯誤:發送後無法設置標題

我已閱讀其他帖子,但我不明白。我沒有任何雙重回調或任何東西。我的代碼在哪裏導致這個錯誤?

 
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'); 
}); 
+0

此特定錯誤是由於操作引起的事情失序在發送響應異步操作不當幾乎總是。 – jfriend00

+0

我的代碼中是否有導致此問題的任何內容?我應該在哪裏看? – user3658794

+0

請發佈錯誤的堆棧跟蹤('error.stack')。 – Dai

回答

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 
    }); 
+0

OP已經修改了他的Q來刪除對'res.end()'的調用。 – Dai

+0

@戴 - 很難跟上一個不斷變化的問題。另一個問題是,在所有數據都被接收之前,他們不應該調用'res.render()'。重點是應該收集所有的數據,然後當收到所有數據時,他們可以用'res.render()'創建響應。 – jfriend00

+0

@Dai'result'發射給每一行。如果有多行,'res.render()'將被多次調用。 – mscdex

相關問題