0
我正在開發一個網絡應用程序,其中有一個數據庫用於遊戲數據,當您點擊任何遊戲時,我向API發出GET請求。我希望我的應用程序能夠工作,以便您可以點擊任何一款遊戲,並且您可以使用請求中的額外信息填充該遊戲的頁面,而無需爲每個遊戲提前發送GET請求(約200張) ,但我有以下問題:NodeJS:有多個GET請求的錯誤
_http_outgoing.js:344
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_outgoing.js:344:11)
at ServerResponse.header (C:prototype\node_modules\express\lib\response.js:718:10)
at ServerResponse.send (C:prototype\node_modules\express\lib\response.js:163:12)
at ServerResponse.json (C:prototype\node_modules\express\lib\response.js:249:15)
at EventEmitter.<anonymous> (C: prototype\webapp.js:182:14)
at emitNone (events.js:72:20)
at EventEmitter.emit (events.js:166:7)
at IncomingMessage.<anonymous> (C:webapp.js:237:17)
at emitNone (events.js:72:20)
at IncomingMessage.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:913:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
這裏是我試圖運行代碼:
req = https.request(options, function(res) {
var responseBody ="";
res.setEncoding("UTF-8");
//retrieve the data in chunks
res.on("data", function(chunk) {
responseBody += chunk;
});
res.on("end", function(){
//Once completed we parse the data in JSON format
sendData = JSON.parse(responseBody);
console.log(sendData);
eventEmitter.emit('got_data');
});
});
req.on("error", function(err) {
console.log(`problem with request: ${err.message}`);
});
req.end();
這裏是它的路由:
app.get('/api/gameDetails', function(req, res) {
var device = req.query.device;
var id = req.query.id;
requestForGameDetails(id, device);
eventEmitter.on('got_data', function() {
return res.json(sendData);
});
});
我環顧四周,我知道這個問題是在'返回res.json(sendData);'因爲它被調用兩次,但我想修復它,以便它不再是一個問題。 – KC32
嘗試使用eventEmitter.once而不是eventEmitter.on在您的獲取路線代碼 – vbranden
謝謝你的工作! :)你可以正式提交它作爲迴應,所以我可以接受它作爲一種解決方案? – KC32