1

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

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

更新

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

4

3 回答 3

5

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

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

更新

实际上有比我原来的答案更好的方法来做到这一点。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' }} : {}
  },
})
于 2019-11-09T20:01:48.427 回答
2

对于异步令牌设置,您可以使用身份验证交换

import { createClient, dedupExchange, cacheExchange, fetchExchange } from 'urql';
import { authExchange } from '@urql/exchange-auth';

const getAuth = async ({ authState, mutate }) => {
  if (!authState) {
    const token = await getToken();
    const refreshToken = await getRefreshToken();
    if (token && refreshToken) {
      return { token, refreshToken };
    }
    return null;
  }

  return null;
};

const addAuthToOperation = ({ authState, operation }) => {
  if (!authState || !authState.token) {
    return operation;
  }

  const fetchOptions =
    typeof operation.context.fetchOptions === 'function'
      ? operation.context.fetchOptions()
      : operation.context.fetchOptions || {};

  return makeOperation(operation.kind, operation, {
    ...operation.context,
    fetchOptions: {
      ...fetchOptions,
      headers: {
        ...fetchOptions.headers,
        Authorization: authState.token,
      },
    },
  });
};

const client = createClient({
  url: '/graphql',
  exchanges: [
    dedupExchange,
    cacheExchange,
    authExchange({
      getAuthToken,
      addAuthToOperation,
    }),
    fetchExchange,
  ],
});

于 2021-10-19T10:13:12.370 回答
0

这是我使用的,它工作正常:

const client = createClient({
  url: 'yoururl',
  fetchOptions: {
    headers: {
      'content-type': 'application/json',
      'x-hasura-admin-secret':'********'
    },
  },
});
于 2021-04-05T08:34:22.907 回答