【问题标题】:How to convert beforeSend of ajax itno axiosajax itno axios的beforeSend如何转换
【发布时间】:2021-11-14 06:35:27
【问题描述】:

我正在从 ajax 切换到 axios,这是我要转换的代码。

$.ajax({
            method: 'GET',
            url: SPSConstants.SPS_BASE_URL + 'api/test?filter=' + encodeURIComponent(JSON.stringify(filter)),
            dataType: 'json',
            beforeSend: function (xhr) {
                SPSUtils.getReqHeader(xhr, self, this, true);
            },
        }).done(function (result) {
            var resultObj = JSON.parse(JSON.stringify(result));
            let totalRecords = resultObj.pageInfo.total;
            let currentPage = self.state.currentPage;
            let currentRecords = resultObj.tollFreeNumberMasters;

            if (totalRecords !== 0 && currentRecords.length === 0) {
                
                self.setState({ currentPage: 1, pageInfo: { ...pageInfo, offset: 0 } }, () => {
                    self.loadTollFreeNumberTblData();
                });
            }
})

我之前使用过 axios,所以没什么大不了的。我面临的唯一问题是将这部分 ajax 代码转换为 axios。

beforeSend: function (xhr) {
    SPSUtils.getReqHeader(xhr, self, this, true);
},

在 axios 中是否有任何 beforesend 等价物?

【问题讨论】:

    标签: javascript reactjs ajax axios


    【解决方案1】:

    看来你想在http请求之前获取xhr对象。 Interceptors 在 Axios 中的功能类似。

    axios.interceptors.request.use(config => {
      console.log(config);
    });
    

    但是,如果您在 Axios 实例上设置拦截器函数,则回调将适用于来自该实例的所有请求。要使回调仅对特定请求起作用,您需要创建并使用新的 Axios 实例。

    const newAxios = axios.create();
    newAxios.interceptors.request.use(config => {
      console.log(config);
    });
    

    【讨论】:

    • 如果答案不是您想要的或缺少的,请告诉我,以便我改进!
    猜你喜欢
    • 1970-01-01
    • 2014-08-01
    • 2019-07-17
    • 2013-04-09
    • 2019-12-17
    • 1970-01-01
    • 2017-10-21
    • 2012-05-17
    • 2013-03-28
    相关资源
    最近更新 更多