How to bring the ajax request header to the background of each page after the user has logged in

users log in to the home page, where there are multiple ajax requests. Each ajax request is now required to include Authorization verification information in the header before each Authorization request

I use jquery ajax"s beforeSend method, but I find that this requires a beforeSend method in every ajax request involved in each current page, and then almost every interface api in network has to have two requests. Although the request is successful, it doesn"t feel good to request twice for each interface

related codes

/ / Please paste the code text below (do not replace the code with pictures)
1, the first ajax

       jQuery.ajax({
                url:"http://10.11.2.61:8091/api/user/add",
      contentType:"application/json;charset=utf-8",
                type:"POST",
                datatype:"JSON",
                beforeSend:function(request){
                  request.setRequestHeader("Authorization","Bearer 2ae53f0f-845a-4e8b-9f33-cf35a81d9ea9");
              },
                data:JSON.stringify(obj),
                success:function(res){
                    //
                    //
                _this.userdata.push(_this.newPeople);
                _this.newPeople = {};
                },
                error:function(err){
                    //
                    console.log(err);
                }
            });

2, second ajax

         jQuery.ajax({
                url:"http://10.11.2.61:8091/api/user/delete/"+m,
                type:"GET",
                datatype:"JSON",
                beforeSend:function(request){
                  request.setRequestHeader("access_token","2ae53f0f-845a-4e8b-9f33-cf35a81d9ea9");
             },
                success:function(res){
                    //
                    //
               _this.userdata.splice(n,1);
                },
                error:function(err){
                    //
                    console.log(err);
                }
            });
            

is there any way to validate a page header only once, and all subsequent ajax requests come with Authorization verification in the header


jQuery.ajaxSetup ([options])


you can also encapsulate a method yourself

var access_token = "2ae53f0f"
function post(options) {
    if (access_token) {
        options.headers = {
            access_token : access_token
        }
    }
    jquery.ajax(options)
}
Menu