繁体   English   中英

Node.js-发送标头后无法发送标头

[英]Node.js - Can't send headers after they are sent

我发现最接近的问题在这里 我相信从我的.end()调用设置过程中会收到此错误。 这是我们正在使用的代码:

app.get('/anihome',function(req,res){

var context = {};

function renderPage(context) {
    res.render('anihome',context);
}

function addRequestToPage(text) {
    context.data = text.toString('utf8');
    context.info = JSON.parse(text);
    return context;
}

function addAnimeToPage(text) {
    context.anime = JSON.parse(text);
    return context;
}

function addAnimeRequest(context) {
   var options2 = {
    host: 'anilist.co',
    path: '/api/anime/20631?access_token=' + context.info.access_token,
    method: 'GET'
    };

    https.request(options2, function(restRes) {
        restRes.on('data',function(jsonResult) {
            //context.anime = JSON.parse(jsonResult);
            //console.log(JSON.parse(jsonResult));
            console.log(context);
            renderPage(context);
        });
    }).end();
}
function addHeaderRequest(context) {
    var options = {
    host: 'anilist.co',
    path: '/api/auth/access_token?grant_type=client_credentials&client_id='
    + clientID + '&client_secret=' + secretKey,
    method: 'POST'
    };     

    https.request(options, function(restRes) {
        restRes.on('data', function(jsonResult) {
            context = addRequestToPage(jsonResult);
            addAnimeRequest(context);
        });
    }).end();
}
addHeaderRequest(context);
});

我试图用回调.end(addAnimeRequest(context));设置一个.end() .end(addAnimeRequest(context)); ,这使我出现套接字挂起错误,因此,我的addAnimeRequest函数中的某些内容可能花费了太长时间?

有没有更好的方法可以使用不同的选项向同一网站发出多个请求? 我对Node.js很陌生。

data事件可以发出多次。 您将需要为end事件添加一个侦听器,然后传递所有数据。 例:

https.request(options2, function(restRes) {
    var buf = ''
    restRes.on('data',function(jsonResult) {
        //context.anime = JSON.parse(jsonResult);
        //console.log(JSON.parse(jsonResult));
        buf += jsonResult
    });
    restRes.on('end', function() {
      // TODO JSON.parse can throw
      var context = JSON.parse(buf)
      renderPage(context)
    })
}).end();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM