首页 > 解决方案 > Github GraphQL API 链接未通过 React Web App 获取数据,发现错误

问题描述

我想创建一个反应网络应用程序,它使用 GitHub graphql API 从 github 输出数据。所以我使用了一种我在创建天气网络应用程序时使用的方法,该应用程序仍然使用 graphql 并做出反应,但我的应用程序抛出错误,因为无法从 GitHub 获取数据。控制台中返回的错误表明它是一个 401 后错误,与我添加为我的 URI 的链接相关联,即https://api.github.com/graphql。我现在在我的存储库中有 Web 应用程序。下面是浏览器控制台上显示的错误和我的代码的三个文件。先感谢您。包含代码的三个文件:• App.js

在此处输入图像描述


import './App.css';
import Home from "./Pages/Home.jsx";
import { ApolloClient, InMemoryCache, ApolloProvider } from "@apollo/client";

function App() {

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    uri: "https://api.github.com/graphql",
  });

  return (
    <ApolloProvider client={client}>
      <Home />
    </ApolloProvider>
  );
}

export default App;

• Home.jsx

import { useLazyQuery } from "@apollo/client";
import { GET_REPO_OWNER_NAME } from "../graphql/Queries.js";


const Home = () => {

  const [getRepoName, {loading, data, error}] = useLazyQuery(GET_REPO_OWNER_NAME);

  if(error) return <h1>Error found</h1>
  if(data){
    console.log(data);
  }

  return (
    <div className="home">
      <h1>Github Issue Tracker</h1>
      <input type="text" placeholder="City name..." />
      <button onClick={ () => getRepoName() }>Search</button>
    </div>
  );
};

export default Home;

• Queries.js

import { gql } from "@apollo/client";

export const GET_REPO_OWNER_NAME = gql `
  query { 
    viewer { 
      login
    }
  }
`;

标签: javascriptreactjsgraphqlapollogithub-graphql

解决方案


您的代码中缺少身份验证令牌,请在此处查看如何创建一个。

在有关 graphql的官方GitHub 文档中指定了您需要一个 OAuth 令牌,并且存在一些资源限制

要与 GraphQL 服务器通信,您需要一个具有正确范围的 OAuth 令牌。

按照“创建个人访问令牌”中的步骤创建令牌。您需要的范围取决于您尝试请求的数据类型。例如,选择用户范围以请求用户数据。如果您需要访问存储库信息,请选择适当的存储库范围。

用这个更新你的App.js文件:

import './App.css';
import Home from "./Pages/Home.jsx";
import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from "@apollo/client";
import { setContext } from '@apollo/client/link/context';

function App() {

    // Set your localstorage variable called token
    localStorage.setItem('token', 'my-fancy-token-string');

    // Create the http link
    const httpLink = createHttpLink({
        uri: 'https://api.github.com/graphql',
    });

    // Generate and set the header with the auth details
    const authLink = setContext((_, { headers }) => {
        // get the authentication token from local storage if it exists
        const token = localStorage.getItem('token');
        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : "",
            }
        }
    });

    // Generate your client with the authLink and httpLink
    const client = new ApolloClient({
        cache: new InMemoryCache(),
        link: authLink.concat(httpLink)
    });

    return ( <
        ApolloProvider client = { client } >
        <
        Home / >
        <
        /ApolloProvider>
    );
}

export default App;

更多细节可以查看阿波罗的官方文档

注意:请记住,OAuth 令牌就像您的帐户密码,因此您必须对其保密并且不要共享它,请注意在更新代码时不要将其推送到 github 上。为避免任何问题,请不要将令牌保留在代码中,localStorage.setItem('token', 'my-fancy-token-string');而是将其作为环境变量。

您可以在 linux 上执行此操作,例如export MYTOKEN=my-fancy-token-string. 在您的代码中,您可以使用const token = process.env.MYTOKEN;

从环境变量中读取的代码:

import './App.css';
import Home from "./Pages/Home.jsx";
import { ApolloClient, InMemoryCache, ApolloProvider, createHttpLink } from "@apollo/client";
import { setContext } from '@apollo/client/link/context';

function App() {
    // Create the http link
    const httpLink = createHttpLink({
        uri: 'https://api.github.com/graphql',
    });

    // Generate and set the header with the auth details
    const authLink = setContext((_, { headers }) => {
        // get the authentication token from env variables if it exists
        const token = process.env.MYTOKEN;

        // return the headers to the context so httpLink can read them
        return {
            headers: {
                ...headers,
                authorization: token ? `Bearer ${token}` : "",
            }
        }
    });

    // Generate your client with the authLink and httpLink
    const client = new ApolloClient({
        cache: new InMemoryCache(),
        link: authLink.concat(httpLink)
    });

    return ( <
        ApolloProvider client = { client } >
        <
        Home / >
        <
        /ApolloProvider>
    );
}

export default App;

推荐阅读