从nodejs的请求模块调用时,github搜索api未给出结果

时间:2018-09-07 08:31:31

标签: node.js curl github-api

我正在尝试从搜索类别下的组织的所有存储库中获取结果。如下所示,使用curl命令可以正确获取结果

curl -H "Authorization: token ****" -i https://api.github.com/search/code?q=org:<org>+<search_param>

但是当我尝试通过request模块在nodejs中以编程方式运行它时,它没有返回任何结果。 我的代码如下所示

const request = require("request");
const options = {
    url:'https://api.github.com/search/code?q=org:<org>+<search_param>'
    headers: {
        "Autorization": "token ***",
        "User-Agent": "request"
    },
    json:true
}
console.log(options);
request.get(options, function (error, response, body) {
    console.log('error:', error); // Print the error if one occurred
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
    console.log('body:', body); // Print the HTML for the Google homepage.
});

以上代码的输出如下

body: {"total_count":0,"incomplete_results":false,"items":[]}

请让我知道以上代码有什么问题,或者如果我缺少任何内容。

1 个答案:

答案 0 :(得分:1)

我能够通过使用axios模块而不是request模块来解决此问题,因为request模块未发送Authorization hader。从Nodejs request module doesn't send Authorization header获得了参考。

有效的更新代码如下

const axios = require("axios");
const options = {
    method:"get",
    url:'https://api.github.com/search/code?q=org:<org>+<searchtoken>',
    headers: {
        "Authorization": "token ***",
        "User-Agent": "abc"
    }
}
console.log(options);
axios(options).then(function ( response) {
    console.log('statusCode:', response); // Print the response status code if a response was received
    // console.log('body:', body); // Print the HTML for the Google homepage.
}).catch(function (error) {
    console.log(error);
});

感谢@ mehta-rohan的帮助