action
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));
}
我在这里找到了解决方案,但是它对我不起作用,我需要设置授权标题以在中间件中的请求。如何实施它?怎么了?
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之后输入了中间件,必须以前的中间件。