Github GraphQL API link 未通过 React Web App 获取数据,发现错误

Github GraphQL API link not fetching data through React Web App, Error Found

我想创建一个 React Web 应用程序,它使用 GitHub graphql API 从 github 输出数据。所以我用了我在创建weather web app which still uses graphql and react but my app throws an error because the data cannot be feteched from GitHub. The error returned in the console indicates it is a post 401 error associated with the link I add as my URI which is https://api.github.com/graphql . I have the web app as it is right now on my repository. Below is the error shown on the browser console and the three files of my code. Thankyou in advance.



三个文件时使用的方法,代码为:
• 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
    }
  }
`;

您的代码中缺少授权令牌,请查看here如何创建一个。

在官方GitHub docs about graphql is specified you need an OAuth token and there are some resource limitations

To communicate with the GraphQL server, you'll need an OAuth token with the right scopes.

Follow the steps in "Creating a personal access token" to create a token. The scopes you require depends on the type of data you're trying to request. For example, select the User scopes to request user data. If you need access to repository information, select the appropriate Repository scopes.

更新您的 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;

更多的细节你可以看看official documentation of apollo

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

您可以像 export MYTOKEN=my-fancy-token-string 一样在 linux 上进行。 在您的代码中,您可以使用 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;