axios 带有reactjs的拦截器无法按预期工作

qfe3c7zg  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(128)

我正试图实现一个全球层面的预加载程序的API请求。我刚试了一下样品。但不管用如何在全球范围内实施拦截器?

import axios from 'axios';

export default async (searchTerms) => {
  try {
    const url = `${process.env.SERVICE_URL}/get-jayachan-detais`;
    const params = JSON.stringify({
      orderInfoRequest: {
        searchType: 'MASTER TRX',
        MasterTrxnId: searchTerms.ordnum
      }
    });
    const response = await axios.post(url, params, { withCredentials: true });

    return {
      errors: [],
      response
    };
  } catch (e) {
    return {
      errors: [e]
    };
  }
};

axios.interceptors.request.use(function () {
    console.log('start preloader');
});

axios.interceptors.response.use(function () {
    console.log('stop preloader');
});
zbwhf8kr

zbwhf8kr1#

返回请求拦截器中的config对象和response拦截器中的响应数据/err:

import axios from 'axios';

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    console.log('start preloader');
    return config;
}, function (error) {
    console.error('Error: request interceptor:', error);
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    console.log('stop preloader');
    return response;
}, function (error) {
    console.error('Error: response interceptor:', error);
    return Promise.reject(error);
});

export default async (searchTerms) => {
    try {
        const url = `${process.env.SERVICE_URL}/get-jayachan-details`;
        const params = {
            orderInfoRequest: {
                searchType: 'MASTER TRX',
                MasterTrxnId: searchTerms.ordnum
            }
        };
        const response = await axios.post(url, params, { withCredentials: true });

        return {
            errors: [],
            response: response.data // Return response data
        };
    } catch (e) {
        return {
            errors: [e]
        };
    }
};

此外,假设您得到错误响应,它将帮助您解决和调试问题。

相关问题