什么是fetchKnowingCookie中间件用于react starter kit?

时间:2016-12-13 04:11:38

标签: redux redux-thunk react-starter-kit

查看react starter Kit中的createHelpers.js代码,我发现它在中间件中创建了一个grapqlRequest和一个fetchKnowingCookie方法。

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

这究竟是做什么的?它是否为服务器呈现的提取请求添加了一个cookie头?

我发现它还通过thunk.withExtraArgument将功能传递到中间件,这个额外的行做了什么?这是否意味着可以通过redux异步操作获取带cookie功能的提取?

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,
  };
}

1 个答案:

答案 0 :(得分:0)

它将fetch的修改版本注入到应用于商店的thunk中间件中。

react-starter-kit正在使用node-fetch来处理服务器上的fetch次呼叫。不幸的是,node-fetch doesn't support cookies

每次用户向服务器发出请求时,都会使用req.headers.cookie配置新商店。然后,该cookie对象将用于应用程序中thunks发出的任何fetch请求,从而绕过node-fetch限制。