简体   繁体   中英

Add API Key to graphql request using Apollo Client and React

I did the guide on using GraphQL with Apollo Client and React from the Apollo website and now I want to access a GraphQL API that is protected via an API Key. I have a key but I don't know how to modify my request to use said key.

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'));

you can send in headers as per following way.

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

Here is sample if you like to attach headers as well

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
  }
});

You don't need to use a different version of Apollo to send headers, including auth tokens. You can continue to use apollo-boost by configuring your client like this:

import ApolloClient from "apollo-boost";

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM