可以为 urql 设置自定义标头吗?

tim*_*mbo 3 javascript github graphql urql

Github GraphQL v4 API 具有所谓的架构预览,您可以在其中使用新的架构功能 - 但它需要自定义Accept标头。

我以前使用过 Apollo 客户端,但我想尝试使用 Formidables urlq这个新应用程序。有没有办法使用 urql 客户端设置客户标头?

更新

我认为这已经进入代码库,只是没有记录 - https://github.com/FormidableLabs/urql/pull/96/files

tim*_*mbo 8

查看源代码,以下urqlcreateClient 对我有用:

const client = createClient({
  url: 'https://api.github.com/graphql',
  fetchOptions: {
    headers: {
      Authorization: `bearer ${GITHUB_TOKEN}`,
      Accept: 'application/vnd.github.packages-preview+json',
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

更新

实际上有比我原来的答案更好的方法。createClient接受 的函数fetchOptions。因此,如果令牌存在,它将被添加到Authorization标头中

const client = createClient({
  url: 'http://localhost:8000/graphql/',
  // add token to header if present
  fetchOptions: () => {
    const token = getToken()
    return token ? { headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github.packages-preview+json' }} : {}
  },
})
Run Code Online (Sandbox Code Playgroud)