如何在React Apollo中将标头添加到HttpLink

时间:2019-03-17 18:26:33

标签: reactjs graphql token apollo

我想在我的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}>

3 个答案:

答案 0 :(得分: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)
}

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

希望这会有所帮助。

答案 1 :(得分:1)

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

Link from official documention

答案 2 :(得分:0)

最后,我的朋友建议在context上添加Query,这样就可以了!

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