2016-12-13 8 views
0

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

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

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

私はそれがまた、thunk.withExtraArgument経由でミドルウェアに関数を渡していることがわかります。余分な行は何をしますか?それは、クッキー付きのフェッチ機能がレキシックス非同期アクションから利用可能になることを意味しますか?

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の修正バージョンを注入されます。

react-starter-kitは、サーバーでfetchコールを処理するためにnode-fetchを使用しています。残念ながら、node-fetchdoesn't support cookies

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

関連する問題