In-depth exploration of axios in Vue: a comprehensive guide from basic installation to advanced functional applications


Article Directory

  • Foreword
  • I. axios Request
    • 1. Concept of axios
    • 2. Installation of axios
    • 3. Introduction to axiso Request Mode
    • 4. Axios Request Local Data
    • 5. Axios Cross Domain
    • 6. Axios Global Registration
    • 7. Axios Supported Request Types
      • 1) Get Request
      • 2) Post Request
      • 3) Put Request
      • 4) Patch Request
      • 5) Delete Request
  • II. Axios Advanced
    • 1. Set axios Blocker
      • What is an interceptor
      • Role and use of interceptors
    • 2. Axios package

Foreword

    existVueUnder project,Efficient front-end and back-end communication is key to building a rich user experience。axiosServes as a bridge between front-end and back-end,Its importance is self-evident。This article will take you throughaxiosCharm,From basic concepts、installation method,to advanced application techniques,Help you quickly master theVueused inaxiosconductHTTPThe essence of the request。Not only will we discussaxiosBasic usage of,likeGET、POSTask,Cross-domain configuration will also be explored in depth、Global registration and advanced features such as setting interceptors,Helping you easily achieve elegant front-end and back-end communication。


I. axios Request

1. Concept of axios

Axios is a Promise-based HTTP client for browsers and nodejs. The simple understanding is the ajax seal.

_It has the following characteristics: _

  • Create XMLHttpRequest from Browser
  • Http request from node.js
  • Support for Promise API
  • Block requests and responses
  • Convert Request and Response Data
  • Cancel Request
  • Automatically convert JSON data
  • Client Support Prevent CSRF/XSRF

2. Installation of axios

npm install axios --save 

3. Introduction to axiso Request Mode

_Use format: _

axios.Submission method("Request interface path").then(arrow function).catch(arrow function)

 - Submission methods includeget post delete put wait,
 - .then() Execute after successful requestthenmethod
 - .catch()Execute after request failurecatchmethod 

_For example, a specific use method of the :get is as follows: _

//useaxiossendajaxask,Get all news information
  fnSerachNews(){
      // resultIt is the server’s response to our request.,Request executed successfullythenmethod
      this.$axios.get("http://localhost:8000/news/").then((result) => {
          //passresponseGet specific data,assigned todatadefined innewslist 
          this.newslist = result.data.data
          console.log(result.data.data);
      }).catch((err) => {
          //Request failed to executecatchmethod
          alert(err)
      });
  }, 

4. Axios Request Local Data

_1. Create a new json file under the static folder _

_2. The data.json data format is as follows: _

{
    "first":[
        {"name":"Zhang San","nick":"outlaw"},
        {"name":"John Doe","nick":"little plum"},
        {"name":"Wang Wu","nick":"Xiao Wu"}
    ]
} 

_3. Get local data in the created TestView.vue _

<template>
  <div>
    <button @click="getData">Get local data</button>
    <p>{{ data.first }}</p>
    <ul v-for="(n, index) in data1.first" :key="index">
      <li>{{ n.name }}</li>
      <li>{{ n.nick }}</li>
    </ul>
  </div>
</template>

<script> import Axios from "axios";
export default {
  name: "test",
  data() {
    return {
      // Define variables, object type.
      data1: {},
    };
  },
  methods: {
    getData() {
      //   useaxios Request local data
      //   axios.Request method("Request interface path").then(arrow function).catch(arrow function)
      Axios.get("../../../a.json")
        .then((response) => {
          // Assign the obtained data to the variable,then show
          console.log(response);
          console.log(response.data, typeof response.data);
          this.data1 = response.data;
        })
        .catch((error) => {
          // Request failed
          console.log(error);
        });
    },
  },
}; </script>
<style lang="scss" scoped></style> 

5. Axios Cross Domain

Cross-domain introduction and back-end solution: Point 0.0

_Cross-domain is solved at the front end: _

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave:false, /*Turn off syntax checking*/
  //Enable proxy server(method one)vue3may be caused by the problem,If the first method is not possible,Use the following method
     devServer: {
     proxy: 'http://127.0.0.1:8000'
   }, 
    //Enable proxy server(Method 2)
    devServer: {
    proxy: {
       //The first cross-domain proxy
      '/app': {
        target: 'http://127.0.0.1:8000/', //Interface domain name
        changeOrigin: true,             //Is it cross-domain?
        ws: true,                       //Whether to be an agent websockets
        secure: false,                   //whetherhttpsinterface
        // pathRewrite: {    //Path reset if necessary,can be reset totargetaddress
        //     '^/app':''
        // }
      },
      //Second cross-domain proxy
      '/home': {
        target: 'http://127.0.0.1:8000/',
        ws: true, //for supportwebsocket
        changeOrigin: true //Used to control the request headerhostvalue
        // pathRewrite: {                  //path reset
        //     '^/app':''
        // }
      }
    }
  }
}) 

6. Axios Global Registration

// main.js
import { createApp } from 'vue'
import App from './App.vue'

import  Axios  from "axios";
// After the span is configured,Test Results
// Axios.defaults.baseURL = "http:127.0.0.1:8000"
const app = createApp(App)

app.config.globalProperties.$axios = Axios

app.mount('#app') 

7. Axios Supported Request Types

1) Get Request

_Without request parameters: _

  • Mode 1:
axios.Submission method("Request interface path").then(arrow function).catch(arrow function)

 - Submission methods includeget post delete put wait,
 - .then() Execute after successful requestthenmethod
 - .catch()Execute after request failurecatchmethod 
  • Mode 2: axios.get('/url')

    _With request parameters: _

  • Mode 1:

axios.Submission method("Request interface path").then(arrow function).catch(arrow function)

 - Submission methods includeget post delete put wait,
 - .then() Execute after successful requestthenmethod
 - .catch()Execute after request failurecatchmethod 
*   The requested address is actually http://localhost:8080/url?id=12

* Mode 2: Axios
          methods: ‘get’,
          url: ‘url’,
          params: {
              id:12
           }
        })

2) Post Request

let data = {}
let config = {}
method one:  axios.post('/url',data,config)
Method 2:  axios({
     methods: 'post',
     url: '/url',
     data: data,
     config: config
}) 

3) Put Request

_The request is similar to the post, except that the request method interface is different, and the methods of the incoming object is different. _

4) Patch Request

_The request is similar to the post, except that the request method interface is different, and the methods of the incoming object is different. _

5) Delete Request

axios.delete('/url', {params: {id: 12}}) #The parameters are inurl params---Very important
axios.delete('/url', {data: {id: 12}}) #Parameters are in the request body WillparamsChange to dataJust fine 

II. Axios Advanced

1. Set axios Blocker

What is an interceptor

_Request Request Blocker _: Unified processing before sending a request, such as setting the request header headers, application version number, and terminal type.

_

axios.Submission method("Request interface path").then(arrow function).catch(arrow function)

 - Submission methods includeget post delete put wait,
 - .then() Execute after successful requestthenmethod
 - .catch()Execute after request failurecatchmethod 
``` _: Sometimes we need to perform the next operation according to the status code of the response. For example, since the current token expires and the interface returns 401 unauthorized, we need to log in again.

#### Role and use of interceptors

> _**1\. Function:** _
> 
> *   For example, some information in the config does not meet the requirements of the server, and must be intercepted and changed in time.
> *   For example, each time a network request is sent, a dynamically loaded request icon is displayed on an interface, that is, the user is always circling, so as to let the user know that data is being loaded on a current page, and prepare to render a view.
> *   For example, some network requests (such as logging in to the token) must carry some special information.
> 
>   
> _**2\. Implementation steps:** _


```shell
const instance = axios.create({
  //baseURL:url,
  timeout:5000  // delay
})

1、existrequesr.jsSet request interceptor in
interceptors.request.use()
2、Set up response interceptor
interceptors.response.use() 

_Core Code: _

// request interception
instance.interceptors.request.use(
  function (config) {
    console.group('Global request interception')
    console.log(config)
    return config
  },
  function (err){
    return Promise.reject(err)
  }
)

// response interception
// This method will be executed first after the server returns data.
instance.interceptors.response.use(
   function (response){
     console.group('Global response interception')
     console.log(response)
     return response
   },
  function (err){
     return Promise.reject(err)
  }
) 

2. Axios package

//  utils/request.js
import axios from "axios";
// const baseURL = "http://127.0.0.1:8000"; // Replace it with your ownAPIinterface address
const axiosIns = axios.create({
//   baseURL,
  timeout: 10 * 1000 // The timeout is set to10Second
});
// encapsulationgetask,and expose the encapsulated methods
export const get = (url, params) => {
  return axiosIns.get(url,{params})
}
// encapsulationpostask
export const post = (url, data) => {
  return axiosIns.post(url,data)
}
// encapsulationputask
export const put = (url, data) => {
  return axiosIns.put(url,data)
}
// encapsulationdeleteask
export const del = (url, data) => {
  return axiosIns.delete(url,{data})
}
................................................
// encapsulationget
 get("https:/localhost:8000/news", {
        page: 3,
        per: 3,
      })
        .then((resp) => {
          console.log(resp.data);
        })
        .catch((error) => {
          console.log(error);
        });
....................................................        
// encapsulationpost
post('https:/localhost:8000/news/login',{userName:'xiaoming',password:'111111'})
         .then(res=>{
           console.log(res)
         }).catch(err=>{
         console.log(err)
       }) 

Insert image description here

This text is transferred from https://blog.csdn.net/m0_48173416/article/details/139880221,If there is any infringement,Please contact to delete。