0

反応スターター キットの createHelpers.js コードを調べると、ミドルウェアで grapqlRequest と fetchKnowingCookie メソッドが作成されていることがわかります。

https://github.com/kriasoft/react-starter-kit/blob/feature/redux/src/store/createHelpers.js

これは正確に何をしているのですか?サーバーがレンダリングしたフェッチ要求に Cookie ヘッダーを追加していますか?

を介して関数をミドルウェアにも渡していることがわかりますが、thunk.withExtraArgumentその余分な行は何をしますか? redux async アクションから fetch with cookies 関数が利用可能になるということですか?

import fetch from '../core/fetch';

function createGraphqlRequest(fetchKnowingCookie) {
  return async function graphqlRequest(query, variables) {
    const fetchConfig = {
      method: 'post',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ query, variables }),
      credentials: 'include',
    };
    const resp = await fetchKnowingCookie('/graphql', fetchConfig);
    if (resp.status !== 200) throw new Error(resp.statusText);
    return await resp.json();
  };
}

function createFetchKnowingCookie({ cookie }) {
  if (!process.env.BROWSER) {
    return (url, options = {}) => {
      const isLocalUrl = /^\/($|[^/])/.test(url);

      // pass cookie only for itself.
      // We can't know cookies for other sites BTW
      if (isLocalUrl && options.credentials === 'include') {
        const headers = {
          ...options.headers,
          cookie,
        };
        return fetch(url, { ...options, headers });
      }

      return fetch(url, options);
    };
  }

  return fetch;
}

export default function createHelpers(config) {
  const fetchKnowingCookie = createFetchKnowingCookie(config);
  const graphqlRequest = createGraphqlRequest(fetchKnowingCookie);

  return {
    fetch: fetchKnowingCookie,
    graphqlRequest,
    history: config.history,
  };
}
4

1 に答える 1

0

fetchストアに適用されているサンク ミドルウェアに、修正されたバージョンを挿入しています。

react-starter-kitサーバーで呼び出しnode-fetchを処理するために使用しています。fetch残念ながら、node-fetch は Cookie をサポートしていません

ユーザーがサーバーにリクエストを送信するたびに、 を使用して新しいストアが構成されますreq.headers.cookie。その Cookie オブジェクトはfetch、アプリケーションのサンクによって行われるすべての要求で使用され、node-fetch制限を回避します。

于 2016-12-13T06:10:11.620 に答える