【问题标题】:Add API Key to graphql request using Apollo Client and React使用 Apollo 客户端和 React 将 API 密钥添加到 graphql 请求
【发布时间】:2018-11-29 12:25:42
【问题描述】:

我在 Apollo 网站上完成了将 GraphQL 与 Apollo Client 和 React 一起使用的指南,现在我想访问一个通过 API 密钥保护的 GraphQL API。我有一个密钥,但我不知道如何修改我的请求以使用该密钥。

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import { ApolloProvider } from "react-apollo";
import ApolloClient from "apollo-boost";
import { Query } from "react-apollo";
import gql from "graphql-tag";

const client = new ApolloClient({
    uri: "https://sample-api/graphql"
});

const GetStats = () => (
    <Query
        query={gql`
      {
        player(playername:"Player1){
            statistics
        }
      }
    `}
    >
        {({ loading, error, data }) => {
            if (loading) return <p>Loading...</p>;
            if (error) return <p>Error :(</p>;

            return data.rates.map(({ statistics }) => (
                <div key={statistics}>
                    <p>{`${statistics}`}</p>
                </div>
            ));
        }}
    </Query>
);

const App = () => (
    <div>
        <header>New Project</header>
        <ApolloProvider client={client}>
            <div>
                <h2><GetStats/></h2>
            </div>
        </ApolloProvider>
    </div>
);`enter code here`



ReactDOM.render(<App />, document.getElementById('root'));

【问题讨论】:

  • API key 需要如何发送到服务器? apollo-boostcan be configured 发送 cookie 或标头。
  • 我问了开发人员,它应该通过标题发送。

标签: reactjs api graphql apollo-client


【解决方案1】:

您可以按照以下方式发送标头。

const httpLink = createHttpLink({
    uri: '',
    request: operation => {
        operation.setContext({
          headers: {
            authorization: `Bearer ${process.env.TOKEN}`,
          },
        });
      }
});

【讨论】:

    【解决方案2】:

    如果您也想附加标题,这里是示例

    import config from "./aws-exports";
    import { ApolloProvider } from "@apollo/react-hooks";
    import { ApolloClient, createHttpLink, InMemoryCache } from "@apollo/client";
    import { setContext } from "apollo-link-context";
    .....
    
    const httpLink = createHttpLink({
      uri: config.aws_appsync_graphqlEndpoint
    });
    const authLink = setContext((_, { headers }) => {
      // get the authentication token from local storage if it exists
      const token = sessionStorage.getItem("token");
      console.log("Header in AppSync ", token);
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          authorization: token ? token : ""
        }
      };
    });
    const client = new ApolloClient({
      // uri: config.aws_appsync_graphqlEndpoint,
      link: authLink.concat(httpLink),
      cache: new InMemoryCache(),
      region: config.aws_appsync_region,
      auth: {
        type: config.aws_appsync_authenticationType,
        apiKey: config.aws_appsync_apiKey
      }
    });
    

    【讨论】:

      【解决方案3】:

      您无需使用不同版本的 Apollo 来发送标头,包括身份验证令牌。您可以通过像这样配置您的客户端来继续使用apollo-boost

      import ApolloClient from "apollo-boost";
      
      export default new ApolloClient({
        fetchOptions: {
          credentials: "include"
        },
        headers: {
          // add API key here
        },
        uri: "/api/uri/here"
      });
      
      

      【讨论】:

        猜你喜欢
        • 2020-07-23
        • 2020-02-01
        • 2022-12-12
        • 1970-01-01
        • 1970-01-01
        • 2020-01-07
        • 2020-01-24
        • 2023-03-19
        • 2018-07-18
        相关资源
        最近更新 更多