动作
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,但它对我不起作用,我需要在我的中间件中为请求设置授权标头。怎么实现呢?怎么了?
答案 0 :(得分:0)
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之后输入我的中间件,自己的中间件必须在之前。