我正在询问一种使用 Apollo 为不同查询设置自定义标头的方法。通过 Apollo Docs 上找到的以下代码,使用该客户端变量为所有 HTTP 请求设置标头。有没有办法全局声明变量
authLink
或另一个变量,以便可以在不同的文件和函数中更改它?或者有更好的方法来设置标题吗?任何帮助将不胜感激。谢谢你。
import { ApolloClient, createHttpLink, InMemoryCache } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
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}` : "",
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
setContext
内部的函数将在每次发出传出请求时执行,因此您可以在其中包含任何类型的逻辑,包括从您在代码中其他位置设置的全局变量中读取的逻辑。
也就是说,您还可以将
context
选项传递给 useQuery
调用,因此您也可以使用它来为单个请求设置自定义标头。