【问题标题】:Github API Calls with personal access token Usage with Fetch with node JS and React JS带有个人访问令牌的 Github API 调用 使用 Fetch 与 node JS 和 React JS
【发布时间】:2021-08-11 14:38:33
【问题描述】:

今天,我在玩 GitHub API,遇到了这里描述的每小时 60 次调用的障碍 - https://developer.github.com/v3/rate_limit/

对于命令行测试,解决方案是使用 PAT - https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token

我是新手,但 GitHub 文档有点混乱,所以我跑了很多次。 Github 推荐以下 CURL 用法

curl -u GitHubUserName:personalaccesstoken https://api.github.com/users/GitHubUserName

但是,然后,在 fetch 请求中使用它是一个挑战,因为在如何使用事物的管道中有许多折旧。

那么问题来了,如何最好地在 node JS 和 React JS 中通过简单的 fetch 调用来实现这一点?

【问题讨论】:

    标签: fetch github-api


    【解决方案1】:

    最后,我得到了下面的代码块,让它工作。

    import React, { useState, useEffect } from "react";
        
    function GitHubUser({ login }) {
        const [data, setData] = useState();
        const [error, setError] = useState();
        const [loading, setLoading] = useState(false);
       
        useEffect(() => {
          if (!login) return;
          setLoading(true);
          fetch(`https://api.github.com/users/GitHubUserName`,{
            method: "GET",
            headers: {
              Authorization: `token personalaccesstoken ` 
            }
          })
            .then(data => data.json())
            .then(setData)
            .then(() => setLoading(false))
            .catch(setError);
        }, [login]);
        
        if (loading) return <h1>loading...</h1>;
        if (error)
          return <pre>{JSON.stringify(error, null, 2)}</pre>;
        if (!data) return null;
      
        return (
          <div className="githubUser">
            <img
              src={data.avatar_url}
              alt={data.login}
              style={{ width: 200 }}
            />
            <div>
              <h1>{data.login}</h1>
              {data.name && <p>{data.name}</p>}
              {data.location && <p>{data.location}</p>}
            </div>
          </div>
        );
      }
        
    export default function App() {
      return <GitHubUser login="GitHubUserName" />;
    }
    

    主要的困惑是,在 GitHub 文档的某些部分中,它一直在说我们应该使用用户名,以及基本的和不应该的。也许这只是我的困惑,但这解决了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-02
      • 2023-04-10
      • 1970-01-01
      • 2021-12-12
      • 2021-05-15
      • 2019-12-18
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多