使用请求的请求函数时,Github API使用403进行响应

ada*_*iec 6 request node.js github-api

我正在尝试向github的API发出请求.这是我的要求:

var url = 'https://api.github.com/' + requestUrl + '/' + repo + '/';

request(url, function(err, res, body) {
    if (!err && res.statusCode == 200) {

        var link = "https://github.com/" + repo;
        opener(link);
        process.exit();

    } else {
        console.log(res.body);
        console.log(err);
        console.log('This ' + person + ' does not exist');
        process.exit();
    }

});
Run Code Online (Sandbox Code Playgroud)

这是我得到的答复:

Request forbidden by administrative rules. Please make sure your request has a User-Agent header (http://developer.github.com/v3/#user-agent-required). Check https://developer.github.com for other possible causes.
Run Code Online (Sandbox Code Playgroud)

我过去使用过完全相同的代码,但它已经有效了.请求不会抛出任何错误.现在我很困惑为什么我得到403(禁止)?有解决方案吗

kfb*_*kfb 14

响应中给出URL中所述,对GitHub API的请求现在需要一个User-Agent标头:

所有API请求必须包含有效的User-Agent标头.没有User-Agent标题的请求将被拒绝.我们要求您使用GitHub用户名或应用程序名称作为User-Agent标头值.如果有问题,我们可以与您联系.

request文档特别显示了如何向User-Agent请求添加标头:

var request = require('request');

var options = {
  url: 'https://api.github.com/repos/request/request',
  headers: {
    'User-Agent': 'request'
  }
};

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    var info = JSON.parse(body);
    console.log(info.stargazers_count + " Stars");
    console.log(info.forks_count + " Forks");
  }
}

request(options, callback);
Run Code Online (Sandbox Code Playgroud)


Ern*_*est 7

从 C# 并使用HttpClient你可以做到这一点(在最新的 .Net Core 2.1 上测试):

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Accept.Add( new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

    client.DefaultRequestHeaders.UserAgent.TryParseAdd("request");//Set the User Agent to "request"

    using (HttpResponseMessage response = client.GetAsync(endPoint).Result)
    {
        response.EnsureSuccessStatusCode();
        responseBody = await response.Content.ReadAsByteArrayAsync();
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢