【问题标题】:Node.js - Can't send headers after they are sentNode.js - 发送标头后无法发送标头
【发布时间】:2016-05-22 00:56:17
【问题描述】:

我发现最接近我的问题是here。我相信我的 .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()s 之一,.end(addAnimeRequest(context));,这给我留下了套接字挂起错误,所以大概是我的 addAnimeRequest 函数中的某些东西花费了太长时间?

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

【问题讨论】:

    标签: javascript node.js express handlebars.js


    【解决方案1】:

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-17
      • 2018-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-06-17
      • 2018-05-05
      • 2016-12-19
      相关资源
      最近更新 更多