简体   繁体   English

在 JavaScript 上验证 GitHub API

[英]Authenticate GitHub API on JavaScript

I'm building a simple application on react using axios and the GitHub API, but i'm having problems with the API authentication.我正在使用 axios 和 GitHub API 在 React 上构建一个简单的应用程序,但是我在 API 身份验证方面遇到了问题。

I've manage to get some requests, but I need to authenticate my access since I have a limited number of requests avaliable: "API rate limit exceeded for .我设法收到了一些请求,但我需要验证我的访问权限,因为我的可用请求数量有限:“超出了. . . . . . . (But here's the good news: Authenticated requests get a higher rate limit.)" (但好消息是:经过身份验证的请求获得了更高的速率限制。)”

I've generated a token for a GitHub account but I don't know how to use it.我已经为 GitHub 帐户生成了一个令牌,但我不知道如何使用它。 Here is what I tried:这是我尝试过的:

    const fetchUsers = () => {
        axios.get('https://api.github.com/search/users?q=' + props.user, {
            'auth': {
              'username': my_user,
              'token': my_token,
            }
        })
        .then(response => {
            const users = response.data.items;
            const updatedUsers = users.map(users => {
                return {
                    ...users,
                }
            })
            setUsersLoaded(true)
            setUsers(updatedUsers)
        })
    }

Can I validate it with axios or do I have to work with a different approach?我可以使用 axios 验证它还是必须使用不同的方法?

According to the documentation you have to add an authorization header.根据文档,您必须添加授权标头。

axios.get('https://api.github.com/search/users?q=' + props.user, {
  'headers': {
    'Authorization': `token ${my_token}` 
  }
})

Otherwise github themselves actually offer a library called octokit which you can use instead of axios.否则 github 本身实际上提供了一个名为octokit的库,您可以使用它来代替 axios。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM