节点尝试发送标头但以前的响应似乎仍然打开

时间:2014-03-19 16:11:26

标签: node.js

我有以下代码:

app.get('/pull-requests', function (request) {
  fetchRepos(fetchPullRequests);
  app.on('pull-requests:fetched', function (pullRequestsByRepo) {
    var html = "";

    _.each(pullRequestsByRepo, function (pullRequests) {
      html += 'There is <strong>'+ pullRequests.length +'</strong> pending pull request(s) for <strong>'+ pullRequests[0].title +'</strong>:';
      html += '<ul>';
      _.each(pullRequests, function (pullRequest) {
        html += '<li><em>'+ pullRequest.title +'</em> (<a href="'+ pullRequest.url +'">'+ pullRequest.url +'</a>)</li>';
      });
      html += '</ul>';
    });

    response.send(html);
  });
});

一次正常工作。每隔一个请求就会结束错误Can't set headers after they are sent.


编辑:更多代码来明确逻辑

function fetchRepos (callback) {
  _options.path = '/orgs/'+ app.get('org') +'/repos?client_id='+ app.get('client_id') +'&client_secret='+ app.get('client_secret');

  // Fetch the list of repos for a given organisation
  var request = https.get(_options, function (res) {
    data = "";

    res.on('data', function (chunk) {
      data += chunk;
    });

    res.on('end', function () {
      var repos = JSON.parse(data);
      return callback(repos);
    });
  });

  request.on('error', function (error) {
    console.log('Problem with request: '+ e);
  });
}

function fetchPullRequests (repos) {
  var pullRequests = [];
  _.each(repos, function (repo, index) {
    _options.path = '/repos/'+ app.get('org') +'/'+ repo.name +'/pulls?client_id='+ app.get('client_id') +'&client_secret='+ app.get('client_secret');
    var request = https.get(_options, function (res) {
      (function () {
        var data = "";

        res.on('data', function (chunk) {
          data += chunk;
        });

        res.on('end', function () {
          data = JSON.parse(data);
          if (data.length > 0) {
            pullRequests.push(data);
          }

          if (index == (repos.length - 1)) {
            app.emit('pull-requests:fetched', pullRequests);
          }
        });
      })();
    });
  });
}

1 个答案:

答案 0 :(得分:1)

您的问题是,无论何时拨打app.on('pull-requests:fetched', …),您都会添加一个新的侦听器,这意味着当第二个请求到达时,它将再次触发第一个请求。

节点然后抱怨,因为您尝试回复两次第一次请求。

您可以通过调用app.once来解决您的问题,这可以确保只触发一次,但如果同时有2个请求到达,您仍会遇到问题。

在这种情况下,正确的模式是将回调传递给fetchRepos。