jquery ajax 拦截,axios拦截

最近在做的项目用到了需要在ajax请求之前加参数,

1. 第一种ajax请求拦截

a. https://www.cnblogs.com/pssp/p/5878337.html,这篇文章里提到的是使用ajaxStart和ajaxStop,

具体如下 :$(document).ajaxStart(function(){}).ajaxStop(function(){}),这样的无法获取ajax发送的配置项,只能用来添加londing动画,无法满足要求

b. https://www.cnblogs.com/dingzhipeng/p/8483393.html,使用钩子函数,这个因为又要引入额外的文件,所以并没有尝试

c. 自定义ajax方法,

(function() {

    var _ajax = $.ajax;
    $.ajax = function(opts) {
        //实现自己的逻辑
        _ajax(opts);
    };
})();
这种方式能够满足要求,因为要统一修改ajax请求,所以自己实现最好
下面还有问题,因为是要添加自定义headers信息,所以需要设置headers
https://blog.csdn.net/g_wendy/article/details/80679197,这里提到了两种方式

1.1 setting参数 headers

$.ajax({
    headers: {
        Accept: "application/json; charset=utf-8"
    },
    type: "get",
    success: function (data) {

    }
});

    
 
1.2 beforeSend方法
 
$.ajax({
    type: "GET",
    url: "default.aspx",
    beforeSend: function(request) {
      //这里添加自定义的header request.setRequestHeader("Test", ""); }, success: function(result) { alert(result); } });

2. axios拦截

// 每次请求携带cookies信息,用于跨域处理时
axios.defaults.withCredentials = true;

//axios发送之前的拦截处理

axios.interceptors.request.use(
config => {return config}
)
//axios请求返回后的处理
axios.interceptors.response.use(
function (response) {return response}
)
 
原文地址:https://www.cnblogs.com/wenwenli/p/10375613.html