簡體   English   中英

Apollo GraphQL:在 React 子組件中更改默認標頭

[英]Apollo GraphQL: Change default Header INSIDE React Child Component

我想改變我的阿波羅圖表QL Client的默認的頭一個反應成分,我根本不能設法找到的文檔任何東西。 因此,在我的 index.js 中,我按照描述創建並鏈接了我的客戶端,並添加了一個 JWT 令牌標頭。 但是如果我想更改我的 React 組件中的標頭怎么辦。 例如,我想在重新驗證時替換令牌。

在 Axios 中,你可以簡單地用它做一些事情。

axios.defaults.headers.common['Auth-Token'] = 'foo bar';

我怎么能用 React Apollo 做這樣的事情? 這是我的 index.js 的重要部分

const httpLink = createHttpLink({
    uri: 'https://somesecureapi',
});

const authLink = setContext((_, { headers }) => {

const token = localStorage.getItem('token');
return {
    headers: {
        ...headers,
        authorization: token ? `Bearer ${token}` : "",
    }
}
});

const client = new ApolloClient({
    link: authLink.concat(httpLink),
    cache: new InMemoryCache()
});

我嘗試導出客戶端,然后將其導入組件創建一個新鏈接並更改舊鏈接,但這不起作用。

必須有一些更簡單的方法。 有什么建議

createHttpLink接受fetch選項,您可以在其中自定義您希望fetch的行為。 一個簡單的實現可能如下所示:

import { ApolloProvider, graphql } from "react-apollo";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";

const customFetch = (uri, options) => {
  return fetch(uri, {
    ...options,
    headers: {
      ...options.headers,
      "x-custom-header": "custom value"
    }
  });
};

const fetchLink = createHttpLink({
  uri: "https://graphql-pokemon.now.sh",
  fetch: customFetch
});

const client = new ApolloClient({
  link: ApolloLink.from([fetchLink]),
  cache: new InMemoryCache()
});

正如您在customFetch中看到的,我添加了帶有"custom value" x-custom-header 這將應用於使用此客戶端的所有查詢。 但是,我還為fetch選項傳播options.headers ,因此任何出現的標頭都將通過。

在我們的組件中,我們可以像這樣傳遞額外的標頭:

const WrappedPokemon = graphql(PokemonQuery, {
  options: {
    context: { headers: { "x-another-custom-header": "another custom value" } }
  },
  props: ({ data }) => ({
    loading: data.loading,
    pokemon: data.pokemon || {}
  })
})(Pokemon);

與上面的不同,這個額外的標題只存在於這個查詢中。

我在codeandbox中做了一個簡單的實現,幫助大家理解實現。

結果如下所示: 自定義標頭正在傳遞,是的!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM