如何为端点做全局设置

redux-api-middleware How to do global settings for endpoint

本文关键字:全局设置 端点      更新时间:2023-09-26

redux-api-middleware中,我们可以像下面这样创建一个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报头内容类型和授权令牌设置。

我需要一个地方来全局设置这些设置,从他们的官方文档我无法找到解决方案。有人知道吗?或者你有什么办法做到这一点吗?

提前感谢…

在中间件中,您可以访问存储状态,因此您可以将令牌和其他认证信息放入存储中,然后在中间件中使用它。

我遇到了同样的问题,并以这样的实现结束:

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