Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

javascript - how to add some key to all ajax calls in existing get/post requests

i'm working on a existing big project where i have requirement like

Question: i need to add auth_token to all existing Apis of GET and POST almost 1239 in count. how to intercept all GET,POST to add auth_token.

After intercepting and attaching auth_token all apis must have auth_token key

Here is how i need all apis to be called with auth_token

var AUTH_TOKEN = '8450d1eaf4fe0daf6dd';

//code to intercept all ajax call to add auth_key into it


$.ajax({
   url: 'https://jsonplaceholder.typicode.com/todos/1',
   type:'GET',
   success:function(){
      console.log('sent url must contain auth_token',this.url);
   }
});


$.ajax({
   url: 'https://jsonplaceholder.typicode.com/posts',
   type:'POST',
   data:JSON.stringify({"userId":919,id:966,title:'a'}),
   success:function(){
      console.log('sent data must conatain auth_token',this.data);
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the beforeSend method of $.ajaxSetup to add data to all requests you send.

It's worth noting that even though the property is added, your API still returns an error stating that the auth_token is required. Check the API documentation to ensure that it doesn't need to be sent in the request in a different manner, as a header for example.

var AUTH_TOKEN = '8450d1eaf4fe0daf6dd';

$.ajaxSetup({
  beforeSend: function(jqXHR, settings) {
    if (settings.type === 'GET') {
      settings.url += (settings.url.indexOf('?') == -1 ? '?' : '&') + 'auth_token=' + AUTH_TOKEN
    } else {
      let data = JSON.parse(settings.data || '{}');
      data.auth_token = AUTH_TOKEN;
      settings.data = JSON.stringify(data);
    }
  }
});

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/todos/1',
  type: 'GET',
  success: function() {
    console.log('sent url must contain auth_token', this.url);
  }
});


$.ajax({
  url: 'https://jsonplaceholder.typicode.com/posts',
  type: 'POST',
  data: JSON.stringify({
    "userId": 919,
    id: 966,
    title: 'a'
  }),
  success: function() {
    console.log('sent data must conatain auth_token', this.data);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...