408在NodeJS应用中请求Github API超时

Adr*_*ien 3 https http node.js github-api

按照Github API文档为NodeJS应用创建授权。

我有以下代码:

var _options = {
  headers: {
    'User-Agent': app.get('ORGANISATION')
  },
  hostname: 'api.github.com'
};

var oauth2Authorize = function () {
  var path = '/authorizations?scopes=repo';
  path +=    '&client_id='+ app.get('GITHUB_CLIENT_ID');
  path +=    '&client_secret='+ app.get('GITHUB_CLIENT_SECRET');
  path +=    '&note=ReviewerAssistant';

  _options.path = path;
  _options.method = 'POST';

  var request = https.request(_options, function (response) {
    var data = "";

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

    response.on('end', function () {
      console.log(data);
    });
  });

  request.on('error', function (error) {
    console.log('Problem with request: '+ error);
  });
};
Run Code Online (Sandbox Code Playgroud)

我得到的是:

408 Request Time-out
Your browser didn't send a complete request in time.
Run Code Online (Sandbox Code Playgroud)

进行GET请求虽然可行。

Jon*_*ski 5

http.request()不会立即发送request

随着http.request()一个必须始终调用req.end(),以表示你正在使用的要求做-即使没有数据被写入请求主体。

它打开与服务器的基础连接,但request不完整,因此可以随它发送正文/消息:

var request = http.request({ method: 'POST', ... });

request.write('data\n');
request.write('data\n');
request.end();
Run Code Online (Sandbox Code Playgroud)

而且,无论是否有必要write(),您都必须致电end()完成request并完整发送。否则,服务器最终将迫使打开的连接关闭。在这种情况下,有408回应。