我想向GraphQL后端的每个请求中添加一个授权头。我使用的是Remotbackend。
阿波罗文档中有一个如何添加标题的示例: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来完成这个任务呢?
发布于 2018-01-06 12:58:47
在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();
});这会将标题添加到每个请求!
https://stackoverflow.com/questions/48127267
复制相似问题