如何在 ReactQL 的 GraphQL 后端为每个 Apollo 添加 Header
How do I add a Header to every Apollo to the GraphQL Backend in ReactQL
我想为我向 GraphQL 后端发出的每个请求添加授权 header。
我正在使用 Remotbackend。
Apollo 文档有一个如何添加 header 的示例:
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 做到这一点?
在 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();
});
这会将 header 添加到每个请求!
我想为我向 GraphQL 后端发出的每个请求添加授权 header。 我正在使用 Remotbackend。
Apollo 文档有一个如何添加 header 的示例: 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 做到这一点?
在 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();
});
这会将 header 添加到每个请求!