1

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

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 做到这一点?

4

1 回答 1

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

这会将标头添加到每个请求中!

于 2018-01-06T12:58:47.137 回答