Apollo Link 响应头 [英] Apollo Link response headers

查看:30
本文介绍了Apollo Link 响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个简单的 React 应用程序中使用最新版本的 Apollo Client,我试图从用于显示返回的记录集大小的响应中提取标头值.

I am using the latest version of Apollo Client in a simple React app and I am trying to pull out a header value from the response that is being used to show the size of the record set being returned.

我很欣赏这不是提供结果集大小的最优雅的方式,但这就是 API 当前的设置方式.

I appreciate that this is not the most elegant way of providing the result set size, but that is how the API has currently been set up.

我希望使用中间件类型选项来执行此操作,但是当我检查响应对象时,我似乎无法提取任何标头.

I was hoping to use the the middleware type options to do this, but when I inspect the response object I can't seem to pull out any headers.

网络跟踪确实显示响应头符合预期,所以我怀疑我误解了如何获取我需要的底层对象.

The network trace does show that the response header is as expected so I suspect I am misunderstanding how to get at the underlying objects that I need.

我已经检查了文档,但没有什么特别明显的,因此这里的问题......

I have checked the documentation, but nothing stands out as obvious hence the question here ...

推荐答案

当后端响应时,headers 应该包括:

When the backend responds, the headers should include:

Access-Control-Expose-Headers: *//或者你的 refreshToken 字段的名称

Access-Control-Expose-Headers: * // or the name of your refreshToken field

这里有完整的代码:

前端:(Apollo & React)

Front End: (Apollo & React)

const httpLink = new HttpLink({ uri: URL_SERVER_GRAPHQL })

// Setup the header for the request
const middlewareAuthLink = new ApolloLink((operation, forward) => {
  const token = localStorage.getItem(AUTH_TOKEN)

  const authorizationHeader = token ? `Bearer ${token}` : null
  operation.setContext({
    headers: {
      authorization: authorizationHeader
    }
  })
  return forward(operation)
})



//After the backend responds, we take the refreshToken from headers if it exists, and save it in the cookie.
const afterwareLink = new ApolloLink((operation, forward) => {
  return forward(operation).map(response => {
    const context = operation.getContext()
    const {
      response: { headers }
    } = context

    if (headers) {
      const refreshToken = headers.get('refreshToken')
      if (refreshToken) {
        localStorage.setItem(AUTH_TOKEN, refreshToken)
      }
    }

    return response
  })
})

const client = new ApolloClient({
  link: from([middlewareAuthLink, afterwareLink, httpLink]),
  cache: new InMemoryCache()
})

在后端(快递).如果我们需要刷新令牌(例如:因为实际的令牌即将过期)

In the backend (express). If we need to refresh the token (e.g: because the actual one is going to expire)

const refreshToken = getNewToken()
res.set({
   'Access-Control-Expose-Headers': 'refreshToken', // The frontEnd can read refreshToken
   refreshToken
})

文档来自:https://www.apollographql.com/文档/反应/网络/网络层/#afterware

这篇关于Apollo Link 响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆