javascript - 如何在 NextJS 应用程序中从 Apollo 链接上下文访问 Express HTTP 请求?
问题描述
我正在构建一个NextJS
应用程序,并且正在尝试访问 acookie
以便我可以使用它来设置 a Http Header
for 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
,我不知道从哪里可以得到它。
解决方案
我终于找到了办法。每当我从服务器(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.
推荐阅读
- xiaomi - 如何解密小米 [.secretAlbum] 文件夹和文件
- raster - 180 度子午线 (Oceanmap) 上 Chl-a 的缺失数据/0 值
- php - 为什么我的 JSON 文件一次只能更新 1 个字段?
- query-optimization - QLDB sum() 函数是否已优化?
- c# - 测试 GAC 风格的插件架构?
- ruby-on-rails - 如何在 JWT 不记名令牌中设置证书的私钥?
- http - 如何从 HTTPS://some.where/ 向 HTTP://localhost/somephp.php 发送请求?
- python - 使用 Selenium Python 从 CSS 属性中提取文本
- python - 从 Dendrogram 中找到最佳聚类数
- angular - 路由角度