要给 ApolloClient 设置授权头,可以使用 Apollo Link 的 setContext
方法来为每个请求设置授权头。下面是一个示例代码:
import { ApolloClient, InMemoryCache, ApolloLink, HttpLink } from '@apollo/client';
const httpLink = new HttpLink({ uri: 'https://example.com/graphql' });
const authLink = new ApolloLink((operation, forward) => {
// 在这里设置授权头
operation.setContext(({ headers }) => ({
headers: {
...headers,
Authorization: 'Bearer your_token_here',
},
}));
return forward(operation);
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
在上面的代码中,我们创建了一个 authLink
,它是一个 ApolloLink,用于设置授权头。在 authLink
的构造函数中,我们使用 operation.setContext
来设置授权头,其中 your_token_here
是你的授权令牌。
最后,我们将 authLink
和 httpLink
连接起来,并将它们作为 ApolloClient 的链接。这样,每个请求都会经过 authLink
,并在请求头中包含授权信息。