Github API 使用个人访问令牌调用 Fetch with node JS 和 React JS

Github API Calls with personal access token Usage with Fetch with node JS and React JS

今天,我在玩 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

但是,然后,在获取请求中使用它是一个挑战,因为管道中有许多关于如何使用东西的折旧。

所以,问题是,如何最好地在节点 JS 和 React JS 中通过简单的获取调用来实现它?

最终,我得到了以下使其正常工作的代码块。

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 文档的某些部分中,它一直说我们应该使用用户名,基本的,什么不是。也许这只是我的困惑,但这解决了它。