【问题标题】:Next JS:How to get the token stored in the cookie for a server side API call in Next JSNext JS:如何获取存储在 cookie 中的令牌,以便在 Next JS 中进行服务器端 API 调用
【发布时间】:2020-03-30 17:51:10
【问题描述】:

我按照 Next.js 存储库中的示例设置了 apollo 客户端。代码是这样的

import { ApolloClient } from 'apollo-client'
import { InMemoryCache } from 'apollo-cache-inmemory'
import withApollo from 'next-with-apollo'
import { createHttpLink } from 'apollo-link-http'
import fetch from 'isomorphic-unfetch'
import cookie from 'js-cookie'
// Update the GraphQL endpoint to any instance of GraphQL that you like
const GRAPHQL_URL = 'https://myurl.com'
const token = cookie.get('token')
const link = createHttpLink({
  fetch, 
  uri: GRAPHQL_URL,
  headers: {
    authorization: token ? `Bearer ${token}` : '',
  },
})
export default withApollo(
  ({ initialState }) =>
    new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {}),
    }),
)

由于明显的原因,当我尝试从服务器端(在 getInitialProps 中)进行 Graphql API 调用时,由于丢失了 Bearer 令牌,它会引发错误。 我遇到了next-cookie,它可以帮助我在服务器端获取 cookie。 但这需要ctx 变量。如何在此处访问上下文变量 - 或者是否有其他方法可以从服务器端访问存储在 cookie 中的信息?

【问题讨论】:

标签: reactjs next.js


【解决方案1】:

试试这个

import nextCookie from 'next-cookies';
export default withApollo(
  ({ initialState, ctx }) => ...

  const token = nextCookie(ctx);

【讨论】:

  • 我一开始试过这个。但是使用 ({ initialState, ctx })。我收到一个错误Cannot read property 'req' of undefined。显然ctx 在这里未定义。
  • 我已经这样做了。在普通页面中 - ctx 存在。但是在 withApollo 的情况下,ctx 总是未定义的。这对我不起作用。
  • 所以我认为ctxundefined 因为withApollo 在客户端运行,你可以尝试使用document.cookie
  • 适合任何寻求解决方案的人。我最终在客户端使用了 js-cookie,在服务器端使用了 next-cookie。不确定这是否是最好的方法。添加了一个答案。感谢您的帮助:)
【解决方案2】:

对于任何寻求解决方案的人。我最终在客户端使用js-cookie,在服务器端使用next-cookie。不确定这是否是最好的方法。

const token = cookie.get('token')

export default withApollo(
  ({ initialState, ctx }) =>
    new ApolloClient({
      link: createHttpLink({
        fetch,
        uri: GRAPHQL_URL,
        headers: {
          authorization: ctx ? `Bearer ${nextCookie(ctx).token}` : `Bearer ${token}`,
        },
      }),
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {}),
    }),
)

【讨论】:

    猜你喜欢
    • 2021-05-27
    • 1970-01-01
    • 2021-11-20
    • 2019-10-21
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 2020-12-22
    • 2021-01-29
    相关资源
    最近更新 更多