NodeJS:多个GET请求出错

时间:2016-05-21 05:24:25

标签: javascript node.js express

我正在开发一个网络应用程序,我有一个包含游戏数据的数据库,当您点击任何游戏时,我会向API发出GET请求。我希望我的应用程序能够工作,以便您可以点击任何一个游戏,并且您将能够使用请求中的额外信息填充该游戏的页面,而无需为每个游戏预先执行GET请求(大约200个) ,但我遇到以下问题:

    _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);
    });
});

1 个答案:

答案 0 :(得分:1)

您收到错误是因为您正在使用eventEmitter.on,它会持续侦听事件并反过来多次发送结果。因为您只能发送一个响应,您需要使用eventEmitter.once,这将在第一个事件后删除监听器。