首页 > 解决方案 > 从nodejs中的请求模块调用时,github搜索api没有给出结果

问题描述

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

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

但是,当我尝试通过请求模块在 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":[]}

请让我知道上面的代码有什么问题,或者我是否遗漏了什么。

标签: node.jscurlgithub-api

解决方案


我能够通过使用 axios 模块而不是 request 模块来解决这个问题,因为 request 模块不发送 Authorization hader。从 Nodejs 请求模块中获得了一个引用,没有发送 Authorization 标头

更新后的代码如下

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 的帮助


推荐阅读