【发布时间】:2020-04-02 18:20:07
【问题描述】:
我正在构建一个NextJS 应用程序,我正在尝试访问cookie,因此我可以使用它为GraphQL Request 设置Http Header,我正在使用apollo-link-context。这是创建ApolloClient的代码
function createApolloClient(initialState = {}) {
const httpLink = new HttpLink({ uri: `${baseUrl}/graphql`, credentials: 'same-origin', fetch })
const authLink = setContext((_, prevCtx) => {
let token = ''
if (typeof window === 'undefined') token = getCookieFromServer(authCookieName, REQ)
else token = getCookieFromBrowser(authCookieName)
return ({ headers: { 'Auth-Token': token } })
})
const client = new ApolloClient({
ssrMode: typeof window === 'undefined',
cache: new InMemoryCache().restore(initialState),
link: authLink.concat(httpLink)
})
return client
}
这里的问题是 getCookieFromServer 函数需要 Express Request 作为第二个参数,因此它可以从 req.headers.cookie 中提取 cookie,我不知道从哪里可以得到它。
【问题讨论】:
标签: javascript express next.js apollo-client