router.get发送两次发送结果

问题描述 投票:0回答:1

所以我已经用脚本缩小了问题的范围。

问题是这条线

clients.push(res);

似乎正在执行2/3次发射,而不是1次。

在console.log中显示:

STATION_ID Completed
754542
get data connected!
undefined
STATION_ID Stream END
get POdcast ran
STATION_ID Completed
754542
get data connected!
undefined
STATION_ID Stream END
get POdcast ran

但是,当我从clients.push(res);中删除res时,它会正常触发,但不会在浏览器中返回到客户端。

有什么建议吗?

完整代码:

    router.get('/track/:url(*)', (req, res) =>{
    var url = req.params.url.substr(0); 
    console.log('/track/'+url);

    var length = 0;
    var e = 0;
    /* AD SYS */
    var remote = "https://storage.googleapis.com/ad-system/testfolder/OUTOFAREA.mp3";  
    var adsys = needle.get(remote)
    /* PODCAST */
    var filesize = needle.get(url, function(error) {
       if(error){
        e = 505;
        res.send("<html><head></head><body>NOPE</body></html>");
        console.log(error)
        //filesize.end();
        res.end();

       }
    });


        adsys.on('response', function(resB) {
            console.log("STATION_ID Completed");
            length =  Number(resB.headers['content-length']);
           // console.log(length);           
        });

        filesize.on('response', function(resC) {
                console.error("get data connected!");
                console.log(resC.headers['content-length']);
                a = Number(resC.headers['content-length']);
                length = length+a;

      });
      res.set({
        "Content-Type": "audio/mpeg",
        'Transfer-Encoding': 'chunk',
    //    'Content-Disposition': 'attachment',
    //    'Content-Length':length
    });

      adsys.on("finish", function() {

        console.log(" X STATION_ID Stream END");

           getPodcast();



    });  


    adsys.on("data", function (chunk) {
            // console.log(clients.length);
           /* if (clients.length > 0){
                for (client in clients){
                    clients[client].write(chunk);
                    //console.log(chunk);
                };
            }*/
            res.write(chunk);

    });

    function getPodcast(){


        filesize.on("data", function (chunk) {
           res.write(chunk);
        });

        filesize.on('end', function(){
            console.log("end");
            res.end();
        });
    }
});

module.exports = router;
node.js express router
1个回答
0
投票

好的,现在您有了更多的完整代码,因此我可以看到您要完成的工作。

我看到的一些问题:

  1. 未定义变量a,因此它是一个隐式全局变量。那很糟。在本地某个地方声明它。
  2. [计算合并的内容长度时,两个请求之间有完整的竞争条件。您的代码假设adsys首先给您response,但这并不能保证会发生。
  3. 您计算出该长度,但实际上并未使用它。您不能将其放在res.set()指令中,因为在运行时尚未完成计算。
  4. 似乎您至少在adsys请求上似乎缺少错误处理。
© www.soinside.com 2019 - 2024. All rights reserved.