【问题标题】:How in redux-api-middleware add authentication header如何在 redux-api-middleware 中添加身份验证标头
【发布时间】:2017-08-06 12:03:20
【问题描述】:

动作

import { CALL_API } from 'redux-api-middleware';

export const MOVIES_GET_SUCCESS = 'MOVIES_GET_SUCCESS';

export const getMovies = () => {
  return {
    [CALL_API]: {
      endpoint: 'http://localhost:3005/api/movies',
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      },
      types: ['REQUEST', MOVIES_GET_SUCCESS, 'FAILURE']
    }
  };
};

中间件

import { CALL_API } from 'redux-api-middleware';

export default store => next => action => {
  const callApi = action[CALL_API];
  console.log(callApi); // I ALWAYS have undefined 

  if (callApi) {
    callApi.headers = Object.assign({}, callApi.headers, {
      authorization: store.signIn.get('token') || ''
    });
  }

  return next(action);
};

商店

export default function configureStore(initialState = {}) {
   // Middleware and store enhancers
  const enhancers = [
    applyMiddleware(apiMiddleware, authorizationMiddleware),
    window.devToolsExtension ? window.devToolsExtension() : (f) => {
      return f;
    }
  ];

  return createStore(reducers, initialState, compose(...enhancers));
}

我找到了解决方案here,但它对我不起作用,我需要在我的中间件中为请求设置授权标头。如何实施?怎么了?

【问题讨论】:

    标签: api reactjs redux middleware


    【解决方案1】:
    import { createStore, applyMiddleware, compose } from 'redux';
    import { apiMiddleware } from 'redux-api-middleware';
    import reducers from '../reducers';
    import authorizationMiddleware from '../authorizationMiddleware/authorizationMiddleware';
    
    export default function configureStore(initialState = {}) {
       // Middleware and store enhancers
      const enhancers = [
        applyMiddleware(authorizationMiddleware, apiMiddleware),
        window.devToolsExtension ? window.devToolsExtension() : (f) => {
          return f;
        }
      ];
    
      return createStore(reducers, initialState, compose(...enhancers));
    }
    

    解决了,麻烦是因为我在redux-api-middleware之后输入了我的中间件,自己的中间件必须在之前。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-08
      • 2014-06-02
      • 2014-04-29
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多