2016-12-13 33 views
0

通过反应入门工具包中的createHelpers.js代码,我发现它在中间件中创建了一个grapqlRequest和一个fetchKnowingCookie方法。什么是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, 
    }; 
} 

回答

0

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

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

每次用户向服务器发出请求时,都会使用req.headers.cookie配置新的商店。该cookie对象将在您的应用程序中由thunk所做的任何fetch请求中使用,从而解决node-fetch的限制。