如何在redux toolkit查询baseQuery中添加请求和响应错误防范器

mzaanser  于 2022-12-19  发布在  其他
关注(0)|答案(1)|浏览(188)

如何像Redux-toolkit-query一样添加相同的抗受体
添加请求拦截器

axios.interceptors.request.use(function (config) {
            // Do something before request is sent
            return config;
          }, function (error) {
            // Do something with request error
            return Promise.reject(error);
          });

这是redux-toolkit-query的当前实现。现在我想添加请求和响应反接收器。我想一旦用户点击API,如果请求中有错误,它应该拒绝,或者如果错误在response.in,这两种情况下,它都应该拒绝。

export const apiSlice = createApi({
  reducerPath: "api", // optional
  baseQuery: fetchBaseQuery({
    baseUrl: process.env.REACT_APP_BASE_API_URL,
    prepareHeaders: (headers, { getState }) => {
      // const state = getState();
      const token = UTILS.getCurrentUser();
      if (token) {
        headers.set("authorization", token.token);
      }
      return headers;
    },
  }),
  endpoints: (builder) => ({}),
});
bgtovc5b

bgtovc5b1#

我想这可能会帮到你
首先创建axios服务,如下所示:

import axios from 'axios';
import { getCookie, setCookie, deleteCookie } from 'utils/global';

const instance = axios.create({
    baseURL: process.env.REACT_APP_BASE_URL,
    headers: {}
    // headers: { 'X-Custom-Header': 'foobar' }
});

let isRefreshing = false;
let failedQueue = [];

const onErrorResponse = (error) => {
        
    return Promise.reject(error);
};

// Add a request interceptor
instance.interceptors.request.use(
    (config) => {
        // Do something before request is sent
        const newConfig = config;
        const token = getCookie('Token');
        if (token) newConfig.headers.Authorization = `Bearer ${token}`;
        newConfig.headers['Accept-Language'] = 'fa';
        return newConfig;
    },
    (error) => {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
instance.interceptors.response.use((response) => {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
}, onErrorResponse);

export default instance;

然后使用之前创建的Axios服务为RTK查询创建Axios baseQuery。

import axios from 'services/request';

const axiosBaseQuery =
    () =>
    async ({ body, ...restArgs }) => {
        try {
            const result = await axios({ data: body, ...restArgs });
            return { data: result.data };
        } catch (axiosError) {
            const err = axiosError;
            return {
                error: {
                    status: err.response?.status,
                    data: err.response?.data || err.message
                }
            };
        }
    };

export default axiosBaseQuery;

那么在createApi中你可以这样做:

export const ApiSlice = createApi({
    reducerPath: 'api',
    baseQuery: axiosBaseQuery(),
    endpoints: (builder) => ({
      // stuff you like to do
    })

相关问题