Nextjs 和 Apollo:在 getInitialProps 服务器端将 cookie 附加到 Apollo Client
Nextjs & Apollo: Attach cookie to Apollo Client in getInitialProps server side
所以我知道我可以使用 ctx.req.headers.cookie 访问我的 cookie 服务器端,但我不确定如何使用 Apollo 客户端将该 cookie 发送到我的 GraphQL 端点。
有什么帮助吗?谢谢。
我建议的最简单方法是使用 Apollo HTTP Link's context
(https://www.apollographql.com/docs/link/links/http/#passing-context-per-query)
如果您监控网站上的常见 HTTP 请求,您可能会注意到在请求 header 中设置了 cookie
header,代表发送的 cookie。
因此,您可以通过在 Apollo HTTP 客户端的 headers
中设置相同的 cookie
来 send cookies
Apollo
import {
ApolloClient,
InMemoryCache,
gql,
createHttpLink
} from "@apollo/client";
const client = new ApolloClient({
link: createHttpLink({ uri: "https://myserver.com" })
cache: new InMemoryCache()
});
// Pass the cookie header into context when using ApolloClient
const cookie = 'mycookie1=myvalue1; mycookie2=myvalue2';
client.query({
fetchPolicy: "cache-first",
context: {
headers: {
cookie
}
},
query: gql``
});
或者使用 low-level Apollo Link: https://www.apollographql.com/docs/react/api/link/apollo-link-context/#overview
所以我知道我可以使用 ctx.req.headers.cookie 访问我的 cookie 服务器端,但我不确定如何使用 Apollo 客户端将该 cookie 发送到我的 GraphQL 端点。
有什么帮助吗?谢谢。
我建议的最简单方法是使用 Apollo HTTP Link's context
(https://www.apollographql.com/docs/link/links/http/#passing-context-per-query)
如果您监控网站上的常见 HTTP 请求,您可能会注意到在请求 header 中设置了 cookie
header,代表发送的 cookie。
因此,您可以通过在 Apollo HTTP 客户端的 headers
中设置相同的cookie
来 send cookies
Apollo
import {
ApolloClient,
InMemoryCache,
gql,
createHttpLink
} from "@apollo/client";
const client = new ApolloClient({
link: createHttpLink({ uri: "https://myserver.com" })
cache: new InMemoryCache()
});
// Pass the cookie header into context when using ApolloClient
const cookie = 'mycookie1=myvalue1; mycookie2=myvalue2';
client.query({
fetchPolicy: "cache-first",
context: {
headers: {
cookie
}
},
query: gql``
});
或者使用 low-level Apollo Link: https://www.apollographql.com/docs/react/api/link/apollo-link-context/#overview