NodeJS'在发送标头后无法设置标头.' [英] NodeJS 'Can\'t set headers after they are sent.'

查看:70
本文介绍了NodeJS'在发送标头后无法设置标头.'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Express从Twitter提取推特构建了一个应用程序.每个呼叫取回200 twit(如果数目较小,则取较少),总金额为1800.我使用时间间隔取回twits几次,并将最后一个twit的id作为下一个呼叫的第一个twit的id传递.有时效果很好,但有时我会遇到此错误:在发送标头后无法设置标头."

I build an app with Express fetching twits from twitter. Each call is fetching 200 twits (or less if the number is smaller) and total amount is 1800. I use time interval to fetch twits few times and pass id of the last twit as the id of the first twit from next call. Sometimes it works well but sometimes I face this error: 'Can\'t set headers after they are sent.'

我浏览了多个类似的线程,然后更新了错误说明以发送空的res对象.但这并没有改变任何东西.如何解决我的代码以摆脱此错误?

I browsed several similar threads and then updated my error instructions to send empty res objects. But it didn't change anything. How can I fix my code to get rid of this bug?

T.get('statuses/user_timeline', {screen_name: account, count: 200} , function(err, data){
    if(err){return res.send();};

    var i = 0;
    last_id = data[data.length-1].id_str;
    for(var n in data)
    {
        twits.push({content: data[n].text, date: data[n].created_at});
    }
    if(data.length < 200){
        var twitsToSend = filter(twits);
        return res.send(twitsToSend);       
    }

        var getTwits = setInterval(function()
        {
            T.get('statuses/user_timeline', {screen_name: account, count: 200, max_id: last_id},function(err,data){
                if(err){return res.send();};

                last_id = data[data.length-1].id_str;
                if(data.length < 200){
                    var twitsToSend = filter(twits);
                    return res.send(twitsToSend);

                }
                for(var n in data)
                {
                    twits.push({content: data[n].text, date: data[n].created_at});
                }

            });
                ++i;
                if(i==9)
                    {   
                        clearInterval(getTwits);
                        var twitsToSend = filter(twits);
                        return res.send(twitsToSend);
                    };
        },845);

    });
});

推荐答案

您应将 clearInterval(getTwits); 添加到 getTwits 函数的内部:

You should add clearInterval(getTwits); to the inside of the getTwits function:

if(data.length < 200){
                clearInterval(getTwits);
                var twitsToSend = filter(twits);
                return res.send(twitsToSend);
            }

现在,如果Twitter API返回的结果少于200个,则您执行 res.send ,但从不停止间隔计时器,因此它将获取更多结果,然后再次尝试 res.send,这可能是错误的根源.

Right now if the Twitter API returns less than 200 results you do a res.send but never stop the interval timer, so it will fetch more results and again try the res.send, which may be the source of your error.

这篇关于NodeJS'在发送标头后无法设置标头.'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆