SoFunction
Updated on 2025-04-04

Detailed explanation of the simple configuration and use of axios in vue

1. Introduction to axios

axios is an HTTP client based on Promise for browsers and nodejs, which itself has the following characteristics:

  • Create XMLHttpRequest from the browser
  • Make an http request from
  • Support Promise API
  • Intercept requests and responses
  • Convert request and response data
  • Cancel request
  • Automatically convert JSON data
  • Client support to prevent CSRF/XSRF

2. Introduction method:

npm:

$ npm install axios
//Taobao Source$ cnpm install axios

bower:

$ bower install axios

cdn:

<script src="/axios/dist/"></script>

3. Configuration of axios in vue

The previous open source project was planned to use axios from the beginning. I found a lot of articles and strategies online, but found that many of them were not detailed, so I planned to configure one by myself (don’t be timid, roll up my sleeves and just do it).

My configuration:

import axios from 'axios'
import qs from 'qs'
import * as _ from '../util/tool'
 = 5000;            //Response time['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';      //Configure the request header = 'Your interface address';  //Configure the interface address//POST parameter serialization (add request interceptor)((config) =&gt; {
 // Do something before sending the request  if( === 'post'){
     = ();
  }
  return config;
},(error) =&gt;{
   _.toast("Error passing parameters", 'fail');
  return (error);
});
//Return status judgment (add response interceptor)((res) =&gt;{
 //Do something about the response data  if(!){
    // _.toast();
    return (res);
  }
  return res;
}, (error) =&gt; {
  _.toast("Network exception", 'fail');
  return (error);
});
//Return a Promise (send a post request)export function fetch(url, params) {
  return new Promise((resolve, reject) =&gt; {
    (url, params)
      .then(response =&gt; {
        resolve();
      }, err =&gt; {
        reject(err);
      })
      .catch((error) =&gt; {
        reject(error)
      })
  })
}

4. Use configured axios in vue

export default {
  /**
    * User login
    */
  Login(params) {
    return fetch('/users/api/userLogin', params)
  }, 
  /**
    * User registration
    */
  Regist(params) {
    return fetch('/users/api/userRegist', params)
  },
  /**
    * Send registration verification code
    */
  RegistVerifiCode(tellphone) {
    return fetch('/users/api/registVerifiCode', {tellphone: tellphone})
  },
  ......
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.