在使用 Apollo Client HttpLink 的时候,我们可以使用 fetch 来自定义发送请求的行为,从而实现在子域中带有 cookies 的请求。示例代码如下:
import { createHttpLink } from '@apollo/client';
import fetch from 'cross-fetch';
const httpLink = createHttpLink({
uri: 'https://graphql.mydomain.com/graphql',
fetchOptions: {
credentials: 'include'
},
fetch: fetch
});
其中,fetch 参数传入的是一个自定义的 fetch 函数,fetchOptions.credentials 的值为 'include',表示在跨域情况下也可以带上 cookies。
创建 HttpLink 的时候,也可以将其作为参数传入 createApolloClient,示例代码如下:
import { ApolloClient, InMemoryCache } from '@apollo/client';
import { createHttpLink } from '@apollo/client';
import fetch from 'cross-fetch';
const createApolloClient = () => {
const httpLink = createHttpLink({
uri: 'https://graphql.mydomain.com/graphql',
credentials: 'include',
fetch: fetch
});
return new ApolloClient({
link: httpLink,
cache: new InMemoryCache()
});
};
以上两种方式都可以解决 Apollo Client HttpLink 在子域情形下不带有“same-origin”的 cookies 的问题。