首页 > 解决方案 > 如何在 NextJS 应用程序中从 Apollo 链接上下文访问 Express HTTP 请求?

问题描述

我正在构建一个NextJS应用程序,并且正在尝试访问 acookie以便我可以使用它来设置 a Http Headerfor GraphQL Request,我正在使用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函数需要 aExpress Request作为第二个参数,因此它可以从中提取 cookie req.headers.cookie,我不知道从哪里可以得到它。

标签: javascriptexpressnext.jsapollo-client

解决方案


我终于找到了办法。每当我从服务器(in)发送请求时PageComponent.getInitialProps,我都会在上下文中设置标头,然后我可以从以下位置访问它setContext

PageComponent.getInitialProps = async (ctx) => {
  ...
  const token = getCookieFromServer(authCookieName, ctx.req)
  const { data } = await client.query({
    query,
    context: { headers: { 'Auth-Token': token } }
  })
  ...
}

然后在setContext中:

const authLink = setContext((_, prevCtx) => {
  let headers = prevCtx.headers || {}

  if (!headers['Auth-Token']) {
    const token = getCookieFromBrowser(authCookieName)
    headers = { ...headers, 'Auth-Token': token }
  }

  return ({ headers })
})

So if the header is already present in the previous context (which is the case when sent from the server), just use it. If it is not present (when sent from the browser), get the cookie from the browser and set it.

I hope it will help somebody one day.


推荐阅读