如何在ReactQL中向GraphQL后端的每个Apollo添加一个Header

时间:2018-01-06 12:20:23

标签: reactql

我想为每个对GraphQL后端发出的请求添加一个Authorization标头。 我正在使用Remotbackend。

Apollo文档中有一个如何添加标题的示例: https://www.apollographql.com/docs/react/recipes/authentication.html#Header

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = createHttpLink({
  uri: '/graphql',
});

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}` : null,
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

但是我如何使用ReactQL做到这一点?

1 个答案:

答案 0 :(得分:2)

在ReactQL的示例回购中

https://github.com/reactql/example-auth

提到了一种方法:

  config.setApolloNetworkOptions({
    credentials: 'include',
  });

  config.addApolloMiddleware((req, next) => {
    const token = 'the_token'
    req.options.headers = {
      ...req.options.headers,
      authorization: token
    };
    next();
  });

这会为每个请求添加标题!