【问题标题】:What is fetchKnowingCookie middleware used for in the react starter kit?react 入门套件中使用的 fetchKnowingCookie 中间件是什么?
【发布时间】:2017-04-28 01:42:58
【问题描述】:

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

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

这到底是做什么的?是否向服务器呈现的 fetch 请求添加 cookie 标头?

我看到它还通过thunk.withExtraArgument 将函数传递到中间件,那额外的行有什么作用?这是否意味着 redux 异步操作可以使用 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,
  };
}

【问题讨论】:

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


    【解决方案1】:

    它将 fetch 的修改版本注入到应用到存储的 thunk 中间件中。

    react-starter-kit 正在使用node-fetch 处理服务器上的fetch 调用。不幸的是,node-fetchdoesn't support cookies

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 2010-10-10
      • 2017-05-18
      相关资源
      最近更新 更多