Deep analysis of common request method aliases of Axios

Keywords: Javascript axios JSON

The following editor will share a common alias of Axios's request method, which is very comprehensive and detailed, and has a certain reference value. For those who need it, please refer to it for learning. If there are any shortcomings, we welcome criticism and correction.

Axios

Is a promise based HTTP library that can be used in browsers and node.js.
Common request method aliases are: Get/post/http protocol request

Execute Get request

function get(){
 return axios.get('/data.json', {
    params:{
     id:1234
    }
    }).then(function (response) {
     console.log(response);
    })
   .catch(function (error) {
    console.log(error);
   });//Welcome to join the front-end full stack development exchange circle to learn and exchange: 864305860
 }

The params method is used for parameter passing by get method

Execute Post request

function post(){
return axios.post('/data.json', {
  id:1234
    })//Welcome to join the front-end full stack development exchange circle to learn and exchange: 864305860
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });//Welcome to join the front-end full stack development exchange circle to learn and exchange: 864305860
 }

When using post method to transfer parameters, data is directly transferred, which is also the difference between the two methods.

Execute http protocol request

unction http(){
 return axios({
 method: 'post',
 url: '/data.json',
 data: {
  id: 1111,
 },
params: {
 id:2222,
 }).then(res=>{
  this.msg=res.data;
 });//Welcome to join the front-end full stack development exchange circle to learn and exchange: 864305860
}

Note the difference here. When using post request, the data method is used for data transmission, while the params method is used for get request.

Using interceptors:

Intercept requests or responses before they are processed by then or catch.

// Add request interceptor
mounted:function(){
  axios.interceptors.request.use(function (config) {
    // What to do before sending the request
    return config;
   }, function (error) {
    // What to do about request errors
    return Promise.reject(error);
   });
// Add response interceptor
  axios.interceptors.response.use(function (response) {
    // What to do with response data
    return response;
   }, function (error) {
    // What to do about response errors
    return Promise.reject(error);
   });//Welcome to join the front-end full stack development exchange circle to learn and exchange: 864305860
}

epilogue

Thank you for watching. If you have any shortcomings, please correct them.

Posted by turpentyne on Sun, 01 Dec 2019 01:33:07 -0800