将错误响应拦截器放在redux-axios-middleware

时间:2017-04-21 05:41:20

标签: reactjs react-redux axios

我遇到https://github.com/svrcekmichal/redux-axios-middleware的问题。

我想设置拦截器响应(错误)。但无法成功设置它。

这是我的代码:

function interceptorResponse({ dispatch, getState, getAction }, response) {
    console.log(response);
}

export const client = axios.create({
    baseURL: API_URL,
    headers: {
        Accept: 'application/json',
    },
});

export const clientOptions = {
    interceptors: {
        request: [interceptorRequest],
        response: [interceptorResponse],
    },
};

console.log(response)仅在回复为200时才会回复。如何将其设置为接受错误响应?

我尝试过像这样设置

 function interceptorResponse({ dispatch, getState, getAction }) {
    return response => response.data, (error) => {
        const meta = error.response.data.meta;

        const { code, status } = meta;

        console.log(meta);
    };
}

但仍然没有显示任何内容。

任何解决方案?

1 个答案:

答案 0 :(得分:5)

以下是ES6的示例用法:

import axios from 'axios'  
import axiosMiddleware from 'redux-axios-middleware'    

const options = {
        // not required, but use-full configuration option
        returnRejectedPromiseOnError: true,
        interceptors: {
            request: [
                ({ getState, dispatch }, config) => {
                   // Request interception
                  return config
                }
            ],
            response: [
            {
              success: ({ dispatch }, response) => {
                // Response interception
                return response
              },
              error: ({ dispatch }, error) => {
                // Response Error Interception 
                return Promise.reject(error)
              }
            }
          ]
        }
}    
export default axiosMiddleware(axios, options)

请注意,创建的中间件应该传递给createStore()