Use of axios in vue

1, What is Axios

  • Axios is a promise based HTTP Library (similar to jQuery's Ajax for HTTP requests)
  • Can be used for browsers and node JS (it can be used for both the client and the server written by node.js)

2, What are the features of Axios

  • Support promise API
  • Intercept requests and responses
  • Convert request data and response data
  • Cancel request
  • Automatically convert JSON data
  • Client support defense XSRF

3, Axios browser support

4, Installation

1. Use npm:

$ npm install axios

2. Use bower:

$ bower install axios

3. Use cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

5, Usage (vue project built)

1. Basic usage of Axios (get, post, put and other request methods)

First, let's introduce several common request methods of Axios: get, post, put, patch and delete

Get: (generally used to) get data

post: submit data (form submission + file upload)

put: update (or edit) data (push all data to the back end (or server))

patch: update data (only push the modified data to the back end)

Delete: delete data

As an aside, in the actual development process of the project, the general company:

(1) post: generally used to create a new one

(2) put: generally used for updating (suitable for updating with less data)

(3) Patch: generally used for large amount of data; If a form has a large amount of data and many items, using put, pushing all data once is more performance-consuming. At this time, you can consider using patch to push only the modified data to the back end

The above digressions are just common usage and cannot mean that they must be used in this way; Of course, you might say I use post to get data, okay? Of course this is OK. Absolutely no problem! How to use it is still discussed and decided together to avoid unpleasant physical conflict!

Hahaha, it's serious. I'm kidding!

(1) get request

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'

// get request
export default {
  name: "get",
  created() {

    //The first method is called get alias request method
    //http://localhost:8080/static/data.json?id=1
    axios.get('../../static/data.json', {
      params: {//When there are parameters, if there are no parameters, it will be omitted directly
        id: 1
      }
    }).then((res) => {
      console.log('Data:', res);
    })

    //The second way to write
    axios({
      method: 'get',
      url: '../../static/data.json',
      params: {
        id: 1
      }
    }).then((res) => {
      console.log('Data:', res)
    })
  }
}
</script>

<style scoped>

</style>

Here's the request information -

**Status Code:304 Not Modified - * * 304 is redirection; Normally, 200 is returned when accessing the interface for the first time; When you access the interface for the second time, if the data does not change, the browser will automatically recognize and return a status 304, indicating that the data has not been changed or redirected; It is equivalent to redirecting to the resource you just accessed, which will load faster!

(2) post request

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'

// post request
export default {
  name: "post",
  created() {

    /*
    post There are two common request data formats:
    (1)applicition/json
    (2)form-data Form submission (image upload, file upload)
     */

    //The first method is called post alias request method
    // http://localhost:8080/static/data.json?id=1
    // Application / JSON request
    let data = {
      id: 1
    }
    axios.post('../../static/data.json', data)
      .then((res) => {
        console.log('Data:', res);
      })
    //The second way to write
    axios({
      method: 'post',
      url: '../../static/data.json',
      data: data,
    }).then((res) => {
      console.log('Data:', res)
    })
    // Form data request
    let formData = new FormData()
    for (let key in data) {
      formData.append(key, data[key])
    }
    axios.post('../../static/data.json', formData)
      .then((res) => {
        console.log('Data:', res);
      })
  }
}
</script>

<style scoped>

</style>

Find out the differences between the content type and parameters of the two post requests -

  •   applicition/json: As shown below
    

  •   form-data: As shown below
    

(3) put and patch requests

  • The usage of request / put is the same as that of request / JSON, but it is similar to that of request / put!

    mmmm

(4) delete request

  • The delete request is slightly different from the first four requests: the delete request sometimes needs to splice the parameters to the URL, and sometimes put the parameters in the request body like the post request. As for how to call, you need to discuss with the backend!

    mmmm

Find out the difference between splicing parameters on the URL and putting them in the request body -

  • params (splice parameters to URL), as shown below:

  • data (put the parameters in the request body), as shown in the following figure:

(5) Concurrent request

Concurrent request: multiple requests are made at the same time and the return value is processed uniformly.

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'

// Concurrent request
export default {
  name: "get",
  created() {

    // Concurrent requests use two methods of axios: axios All ('parameter is an array '), axios Spread ('callback function ')
    axios.all([
      axios.get('../../static/data.json'),
      axios.get('../../static/city.json')
    ]).then(axios.spread((dataRes, cityRes) => {
      console.log(dataRes, cityRes)
    }))
  }
}
</script>

<style scoped>

</style>

2. Advanced usage of Axios (instance, configuration, interceptor, cancellation request, etc.)

(1) axios instance and configuration

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'
// axios instance
// There are multiple back-end interface addresses, and the timeout length is different
export default {
  name: "get",
  created() {
    //Create an axios instance
    let instance = axios.create({//Parameter configuration
      baseURL: 'http://localhost:8080 ', / / requested domain name (or base address)
      timeout: 3000,//The timeout duration of the request (default: 1000 milliseconds (ms). If it exceeds this duration, 401 timeout will be reported)
      //url: '../../static/data.json ', / / path of the request
      //method: 'get', / / request method
      headers: {//Set the request header (add some parameters to the request header)
        token: ''
      },
      //params: {id: 1}, / / the request parameters are spliced on the URL
      //data: {id: 1} / / put the request parameters in the request body
    })
    instance.get('../../static/data.json', {
      params: {
        id: 1
      }
    })
      .then((res) => {
        console.log(res)
      })
    //If there are two domain names or the timeout duration is different, you can create another axios instance
    let instance2 = axios.create({
      baseURL: 'http://localhost:9090',
      timeout: 5000
    })
    instance2.get('../../static/data.json', {
      params: {
        id: 1
      }
    })
      .then((res) => {
        console.log(res)
      })

    //1.axios global configuration
    axios.defaults.baseURL = 'http://localhost:8080';
    axios.defaults.timeout = 3000;
    //2.axios instance configuration
    let instance = axios.create();
    instance.defaults.timeout = 4000;
    //3.axios request configuration
    instance.get('../../static/data.json', {
      timeout: 6000
    })
      .then((res) => {
        console.log(res)
      })
    //Priority from low to high: 1 Axios global configuration < 2 Axios instance configuration < 3 Axios request configuration
  }
}
</script>

<style scoped>

</style>

(2) Interceptor

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'
// Interceptor: intercepts requests or responses before they are processed
// Request interceptor, response interceptor
export default {
  name: "get",
  created() {
    //request interceptor 
    axios.interceptors.request.use(config => {
      //What to do before sending a request
      return config;
    }, err => {
      //What to do when the request is wrong
      return Promise.reject(err);
    })

    //Response interceptor
    axios.interceptors.response.use(res => {
      //The request succeeded in processing the response data
      return res;
    }, err => {
      //What to do in response to errors
      return Promise.reject(err);
    })

    //Cancel interceptor (understand)
    let interceptors = axios.interceptors.request.use(config => {
      config.headers = {
        auth: true
      }
      return config;
    })
    axios.interceptors.request.eject(interceptors);

    //Example: the login status (token: '') requires the login interface
    let instance = axios.create({});
    instance.interceptors.request.use(config => {
      config.headers.token = '';
      // config.headers = {/ / this writing method will overwrite other parameters in headers, resulting in only the token parameter in headers. Therefore, this writing method is not recommended
      //   token: ''
      // }
      return config;
    }, err => {
      return Promise.reject(err);
    })

    //Pop up window at mobile end
    let instance_phone = axios.create({});
    instance_phone.interceptors.request.use(config => {
      $('#modal').show();
      return config;
    })
    instance_phone.interceptors.response.use(res => {
      $('#modal').hide();
      return res;
    })
  }
}
</script>

<style scoped>

</style>

(3) Cancel request

<template>
  <div>
    <div>mmmm</div>
  </div>
</template>

<script>
import axios from 'axios'
// Cancel request
export default {
  name: "get",
  created() {
    
    //Cancel request: used to cancel the ongoing http request (as an understanding)
    let rource = axios.CancelToken.source();
    axios.get('../../static/data.json', {
      cancelToken: rource.token
    })
      .then((res) => {
        console.log(res)
      })
    .catch((err) => {
      console.log(err)
    })
    //Cancel request (message optional)
    rource.cancel('cancel http');

  }
}
</script>

<style scoped>

</style>

3. Further encapsulation of Axios and its practical application in the project

  • In the vue project, we usually use the axios library to interact with the background to obtain data. It is an http Library Based on promise, which can run on the browser and node JS. axios has many excellent features, such as intercepting requests and responses, canceling requests, transforming json, client defense XSRF, etc.
  • In a complete project, the interaction with the server will be very frequent. A project will have many requests and redundant code. Therefore, it is necessary to encapsulate the request and manage it uniformly.
  • The main purpose of axios encapsulation introduced in this paper is to help us simplify the project code and facilitate the later update and maintenance.

(1) Step 1: Src / API / request js

import axios from 'axios'
// import Vue from 'vue';
// import store from '../store';
// import {router} from '../router/index';

// let vm = new Vue();

const instance = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 3000,
  // headers: {
  //   post: {
  //     'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  //   }
  // }
})

// Request interception
instance.interceptors.request.use(config => {
  // Customize the header and add item token
  // if (store.state.app.token) {
  //   config.headers.token = store.state.app.token;
  //   config.headers.timestamp = new Date().getTime();
  // }
  return config;
}, error => {
  return Promise.reject(error);
})

// Response interception
instance.interceptors.response.use(response => {
  // const resCode = response.status;
  // if (resCode === 200) {
  //   return Promise.resolve(response);
  // } else {
  //   return Promise.reject(response);
  // }
  return response;
}, error => {
  // const resCode = error.response.status;
  // switch (resCode) {
  //   case 401:
  //     vm.$Message.error(error.response.data.message);
  //     store.commit('logout', this);
  //     store.commit('clearOpenedSubmenu');
  //     // console.log('token-0', store.state.app.token);
  //     router.replace({
  //       name: 'login'
  //     });
  //     break;
  //   case 404:
  //     vm.$Message.error('network request does not exist ');
  //     break;
  //   case 500:
  //     vm.$Message.error('server connection error ');
  //     break;
  //   //Other status code error prompt
  //   default:
  //     vm.$Message.error(error.response.data.message);
  // }
  return Promise.reject(error);
})

/*
 *Encapsulate get method
 *@param{String} url [[request address]
 *@param{Object} params Request parameters
 */
export function Get(url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error.data);
    })
  })
}

/**
 *Encapsulate post method
 *@param{String} url Request address
 *@param{Object} params Request parameters
 */
export function Post(url, params) {
  return new Promise((resolve, reject) => {
    instance.post(url, params).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error.data);
    })
  })
}

/**
 *Packaging method
 *@param{String} url Request address
 *@param{Object} params Request parameters
 */
export function Put(url, params) {
  return new Promise((resolve, reject) => {
    instance.put(url, params).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error.data);
    })
  })
}

/**
 *Encapsulation patch method
 *@param{String} url Request address
 *@param{Object} params Request parameters
 */
export function Patch(url, params) {
  return new Promise((resolve, reject) => {
    instance.put(url, params).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error.data);
    })
  })
}

/**
 *Encapsulate delete method
 *@param{String} url [[request address]
 *@param{Object} params [[request parameters]
 */
export function Delete(url, params) {
  return new Promise((resolve, reject) => {
    instance.delete(url, {
      params: params
    }).then((res) => {
      resolve(res.data);
    }).catch((error) => {
      reject(error.data);
    })
  })
}

(2) Step 2: Src / API / index js

import {Get,Post,Put,Patch,Delete} from "@/api/request";

export default {
  getListData: (params) => {
    return Get('../../static/data.json',params);
  },
  postListData: (params) => {
    return Post('../../static/data.json',params);
  },
  deleteListData: (params) => {
    return Delete('../../static/data.json',params);
  }
}

(3) Step 3: Src / main js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store/store'
import Api from './api/index';

Vue.config.productionTip = false
Vue.prototype.$axios = Api;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

(4) Step 4: Src / components / HelloWorld vue

<template>

</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {}
  },
  methods: {
    getData() {
      let data = {
        id: 1
      }
      this.$axios.getListData(data)
        .then((res) => {
          console.log(res);
        })
    },
    postData() {
      let data = {
        id: 1,
        msg: 2
      }
      this.$axios.postListData(data)
        .then((res) => {
          console.log(res);
        })
    },
    postFormData() {
      let data = {
        id: 1,
        msg: 2
      }
      let formData = new FormData();
      for (let key in data) {
        formData.append(key, data[key]);
      }
      this.$axios.postListData(formData)
        .then((res) => {
          console.log(res);
        })
    },
    deleteData() {
      let data = {
        id: 1
      }
      this.$axios.deleteListData(data)
        .then((res) => {
          console.log(res);
        })
    },
  },
  created() {
    this.getData();
    this.postData();
    this.postFormData();
    this.deleteData();
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

Keywords: Javascript Front-end ECMAScript html

Added by marc2000 on Mon, 07 Mar 2022 02:43:07 +0200