【发布时间】: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 中的信息?
【问题讨论】:
-
使用 setContext 吗?来自'apollo-link-context'apollographql.com/docs/react/networking/authentication
-
这可以在服务器端访问吗?