我按照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中存储的信息的另一种方法?
答案 0 :(得分:1)
尝试一下
import nextCookie from 'next-cookies';
export default withApollo(
({ initialState, ctx }) => ...
const token = nextCookie(ctx);
答案 1 :(得分:0)
任何寻求解决方案的人。我最终在客户端使用了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 || {}),
}),
)