0

redux-api-middleware我們可以創建類似下面一個API調用做全局設置,終極版的API中間件如何爲端點

export function loadUsers() { 
    return { 
    [CALL_API]: { 
     headers: { 'Content-Type': 'application/json' }, 
     endpoint: 'http://localhost:1337/users', 
     method: 'GET', 
     types: [LOAD_USERS_REQUEST, LOAD_USERS_SUCCESS, LOAD_USERS_FAILURE] 
    } 
    } 
} 

問題是,爲每個請求,現在用的是共同的終點http://localhost:1337標題內容類型和授權令牌設置。

我需要一個地方來設置全局設置,從他們的官方文檔無法找到解決方案。任何人都知道這一點?或有任何想法來實現這一目標?

在此先感謝..

回答

1

在中間件你可以訪問到店裏的狀態,所以你可以把令牌和其他的認證信息進店,然後在中間件使用它。

我有同樣的問題,並與執行這樣結束:

const callApiMiddleware = store => next => action => { 
    // skip everything which is not API call 
    const callAPI = action[CALL_API] 
    if (typeof callAPI === 'undefined') { 
    return next(action); 
    } 

    // the session info from store 
    const session = store.getState().session; 

    // perform request 
    const {endpoint, headers, method} = callAPI; 
    return fetch(endpoint, { 
    headers: Object.assign({ 
     Authorization: `Bearer ${session && session.token}` 
     // you can add more default headers there if you would like so 
    }, headers), 
    method 
    }); 
}; 
+0

我應該在哪裏把這個代碼,到店配置? –

+0

我明白了,這是我們的自定義中間件,我們應該用'''applyMiddleware'''方法添加這個存儲?對? –

+0

是的,這是自定義中間件。您可以在redux示例中找到類似的內容:https://github.com/reactjs/redux/blob/master/examples/real-world/src/middleware/api.js –