【问题标题】:Receiving 401 "Bad Credentials" when hitting github API endpoint访问 github API 端点时收到 401 “Bad Credentials”
【发布时间】:2017-06-12 01:58:02
【问题描述】:

我正在尝试构建一个使用 GitHub api 的 CLI。我立刻撞上了路障。尽管我已经上下阅读了介绍性文档,但我看不出下面的代码有什么问题。

var userData = require('../userData');
var request = require('request');

module.exports = {
  hitEndpoint: function() {
    var username = "<redacted_user_name>",
        password = "<redacted_password>",
        auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

    var options = {
      method: 'get',
      url: " https://api.github.com/<redacted_user_name>",
      headers: {
        "Authorization": auth,
        "User-Agent": "<redacted_whatever_doesnt_matter>"
      }
    }
    request(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.
    });

  },
}

打印:

error: null
statusCode: 404
body: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}

【问题讨论】:

  • 您尝试访问的端点是api.github.com/username 而不是api.github.com/users/username,我不知道您是只编辑了用户名还是完整路径?
  • 看起来如果我运行相同的请求点击/users/&lt;redacted_user_name&gt; 我确实得到了响应。但是,最初那是完整的路径。在 GH 的“获取您自己的用户资料”下的文档中curl -i -u your_username https://api.github.com/user
  • 它是说你应该点击端点https://api.github.com/user 它将返回你的个人资料,而不是用你自己的用户名替换它:)
  • 另一个我在阅读文档后不清楚的问题是基本身份验证是否足以满足所有 API 操作,因为他们谈论了很多关于 OAuth 和“被身份验证”的内容。如果身份验证凭据与请求同时传入,我不清楚在基本身份验证下可以“被身份验证”的含义。
  • 您可以使用基本身份验证或 OAuth2,它们都适用于整个 API。

标签: node.js github request


【解决方案1】:

要获得您自己的个人资料,您需要点击authenticated user endpoint,您不应将其替换为您自己的用户名,GitHub 会根据您的身份验证字符串知道您是谁:

https://api.github.com/user

要获取其他用户的个人资料,您需要点击users endpoint

https://api.github.com/users/:username

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 2019-07-18
    • 1970-01-01
    • 2018-07-16
    • 2014-06-11
    • 2017-06-16
    • 2018-09-10
    相关资源
    最近更新 更多