【问题标题】:How to add headers to HttpLink in React Apollo如何在 React Apollo 中向 HttpLink 添加标头
【发布时间】:2019-08-08 04:14:42
【问题描述】:

我想在我的 graphql 查询中输入令牌。我必须将身份验证令牌放在哪里?

这是我在 apollo.js 中的代码:

import { withData } from 'next-apollo'
import { HttpLink } from 'apollo-link-http'

export const config = {
  link: new HttpLink({
    uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
    opts: {
      credentials: 'include', // Additional fetch() options like `credentials` or `headers`
    }
  })
}

export default withData(config)

这就是我进行查询的方式:

const MYJOBS = gql`
  {
    myJobs {
      role {
        name
      }
      school {
        name
      }
    }
  }
`

<Query query={MYJOBS}>

【问题讨论】:

    标签: reactjs graphql token apollo


    【解决方案1】:

    根据apollo-graphql 的文档,我们可以使用 setContext 执行此操作 - 在文件顶部安装 apollo-link-context 并执行 import { setContext } from 'apollo-link-context'

    const authLink = setContext((_, { headers }) => {
      // get the authentication token from whereever it exists - This is your choice.
      const token = localStorage.getItem('token');
      // return the headers to the context so httpLink can read them
      return {
        headers: {
          ...headers,
          authorization: token ? `Bearer ${token}` : "",
        }
      }
    });
    
    const httpLink = new HttpLink({
        uri: 'http://localhost:8000/graphql/', // Server URL (must be absolute)
        opts: {
          credentials: 'include', // Additional fetch() options like `credentials` or `headers`
        }
    })
    
    

    然后在你的配置中:

    export const config = {
      link: authLink.concat(httpLink)
    }
    

    这将在我们进行的每个查询中自动包含授权/凭据。

    希望这有帮助。

    【讨论】:

      【解决方案2】:

      最后,我的朋友建议将context 添加到Query 并且成功了!

      <Query
       query={ME}
       context={{
           headers: {
               authorization: JWT ${localStorage.getItem('token')}
           }
       }} >
      

      【讨论】:

        【解决方案3】:

        这是使用@apollo/client的新方法:

        Link from official documention

        【讨论】:

          猜你喜欢
          • 2020-01-20
          • 2020-05-21
          • 2020-06-29
          • 2019-08-22
          • 2019-12-08
          • 2016-04-08
          • 1970-01-01
          • 1970-01-01
          • 2019-08-19
          相关资源
          最近更新 更多