From shallow to deep axios

Traditional Ajax, jQquery-Ajax, Vue-resource, axios... Which strong network requests? The vue framework selects axios. Success is not long-term vision, but you are already standing high.

Preface-Network Module Selection

1. Traditional Ajax
Traditional Ajax is based on XMLHttprequest(XHR)

Very well explained, very confusing configuration and invocation
 It's also very painful to encapsulate
 Understanding the principle is OK. It is seldom used directly in real development. The second is to use jQuery-Ajax

2. jQuery-Ajax
Very useful compared to traditional Ajax

First make it clear that Vue Overall development is not required jQuery Yes
jQuery Code 1 w That's ok, Vue Code is only 1 w That's ok
 There's no need to reference it for network requests at all jQuery

3. Vue-resource
Officially launched, smaller than jQuery

2.0 No more updates and maintenance
 There are a lot of hidden dangers to project development and maintenance

4. jsonp has a look

Download using script tags

Jsonp(JSON with Padding) yes json One"Usage Mode".
Web pages can get data from other domain names (websites), that is, read data across domains.

With this open policy of the < script > element (importing the contents of the script src can be either local or cross-domain), web pages can get JSON data generated dynamically from other sources, and this usage pattern is called JSONP.
The data captured with JSONP is not JSON, but any JavaScript that is executed with a JavaScript literal rather than parsed with a JSON parser.

5. axios
The benefits drip away

 Send in Browser XMLHttpRequest request
 stay node.js Occurs in http request
 Support Promise API
 Intercept requests and responses
 Transform request and response data

Tip: The following is the main body of this article. The following cases can be used as reference.

1. Beginner: axios

1. npm Installation

#Runtime needs, so not--save-dev
npm install axios --save

2. Import

import axios from 'axios'

3. Use

01. Simple use:

//This method requests get by default, and the incoming method:'Request mode'can be changed
    axios({
        url:'Background interface address',
        method:'Request Method'
    }).then(res=>{
        console.log(res);
    })

02. Use with parameters:

    //When carrying parameters, get can be stitched directly to the address
    //This method requests get by default, and the incoming method:'Request mode'can be changed
    axios({
        url:'Background interface address',
        params:{
            //Key-Value Pairs
            age='1',
            name='zhangsan'
        },
        method:'Request Method'
    }).then(res=>{
        console.log(res);
    })

2. Concurrent Requests - Global Configuration

1.axios sends concurrent requests

Remember the last promise sent a concurrent request? Remember to go back and compare insights.

axios sends concurrent requests:

axios.all([

        axios({
            url:''
        }),
        axios({
            url:''
        })

    ]).then(axios.spread((res1,res2)=>{

    })) 

all uses of promise:

Promise.all([

       //First promise
       new Promise((resolve,reject)=>{
           resolve();
       }).then(),

       //Second promise
       new Promise((resolve,reject)=>{
           resolve()
       }).then();

   ]).then(results =>{
       //Wait until both are done, using results[0],results[1]
   })

2.axios global configuration

Let's start with the code to see how axios is configured:

axios({
        baseUrl:'123.123.123.123',
        timeout:1000,
        url:'/home',
        params:{
            //Key-Value Pairs
            age='1',
            name='zhangsan'
        },
        method:'Request Method'
    }).then(res=>{
        console.log(res);
    })

For the above configurations, we can even extract them individually to be globally relevant

axios.defaults.baseUrl='123.123.123.123'
axios.defaults.timeout=1000
axios.defaults.headers.post['ContentType']='application/x-222-form-urlencoded'

Read the official documents in more detail, if necessary

3. axios instances and module encapsulation

1. Scene description:

When we start from axios When a module imports an object, the instance used is the default instance
 When you set some default configurations for this instance, they are fixed
 However, in subsequent development, some configurations may be different
 For example, silent requests need to be specific baseURL perhaps timeout perhaps content-Type etc.
At this point, you can create a new instance and pass in the configuration information for that instance

In vernacular terms, when your business is complex, simply extracting the global configuration is not good, because not all addresses are baseURL s.

2. axios example, simple demonstration:

//Create a corresponding Axios instance using axios.create
 const instance1 = axios.create({
     baseURL:'',
     timeout:1000
 })

//Use the same as axios
//After all, with a baseURL, splicing paths directly is good
 instance1({
     url:'/home'
 }).then(res => {
      console.log(res)
 })

 instance1({
     url:'/home',
     params:{
         age:18,
         name:'Zhang San'
     }
 }).then(res => {
      console.log(res)
 })

3. Packaging

Since each component imports axios, it's cumbersome to write a long list
Solution: Packaging

   Create folders separately network
   Establish request.js file
   To write request.js 
   Open the way to packaging

Packaging_Mode 1 (Callback)

success,failure function as callback function

//success,failure function as callback function
   export function request(config,success,failure){
     //Create axios instance
      const instance = axios.create({
        baseURL:'kzbrise68',
        timeout:1000
      })
     //Send real network requests
      instance(config)
      .then(res => {
          success(res);
      })
      .catch(err => {
          failure(err)
      })
   }

Use:

//For example, main.js
   import {request} from "./network/request"

   request({
       url:'/home'
   },res => {
       console.log(res)
   },err => {
       console.log(err)
   })

Encapsulation_Mode 2 (Callback Advanced)

Modality 1 Upgrade: Advanced Short Form - Drop Parameters in Object

 export function request(config){
     //Create axios instance
      const instance = axios.create({
        baseURL:'kzbrise68',
        timeout:1000
      })

      instance(config.baseconfig)
      .then(res => {
          config.success(res);
      })
      .catch(err => {
          config.failure(err)
      })
   }

Use:

  import {request} from "./network/request"

   request({
       baseconfig{
           url:'/home'
       },
       ,res => {
       console.log(res)
       ,}err => {
       console.log(err)
   }
   })

Encapsulation_Method Three (Promise)

export function request(config){
     return new Promise((resolve,reject) => {
         //Create axios instance
      const instance = axios.create({
        baseURL:'',
        timeout:1000
      })

      instance(config)
      .then(res => {
          resolve(res);
      })
      .catch(err => {
          reject(err)
      })
     })
   }

Use:

 import {request} from "./network/request"

   request({
       url:''
   })
   .then(res => {
       console.log(res);
   })
   .catch(err => {
       console.log(err);
   })

Encapsulation_Mode 4 (Promise Advanced)_Final Solution

Because axios itself is returning promise, so:

export function request(config){
    
      const instance = axios.create({
        baseURL:'',
        timeout:1000
      })

      return instance(config);
     }

Use:

import {request} from "./network/request"

   request({
       url:''
   })
   .then(res => {
       console.log(res);
   })
   .catch(err => {
       console.log(err);
   })

4. axios interceptor

1. Scene description:

To stitch something together, intercept something, add an animation when requested···variety

----All in all, to intercept the request process
axios Interceptor provided
 Used for processing each request we send or receive.

The following code is written in an encapsulated axios where axios is replaced by an instance name

2. Simple Interceptor Demonstration

Request:
axios.interceptors.request.use(config => {
    //Send Successfully
    console.log(config);
    //Remember to go back after interception
    return config;
},err => {
    //Send fails, typically not
    console.log(err)
})

3. Common usage scenarios

Scenario one:

config Information in does not meet server requirements
 Modify header file to make cross-domain, intercept config,Change it and put it back

Scenario 2:

Each time you send a network request, you want to display an icon for the request in the interface
 When sending intercept, show(). In response to interception, close(). 

Scenario three:

Some network requests(Such as login ( token)),This must carry some special information
 Intercept it and jump to the login page

summary

axios is still simpler to use than ajax, and of course the principles of Ajax need to be known.
axios are promise-based, so encapsulation is convenient. Just go back to the instance, and the rest of the n will come out.
The interceptor remembers to return after intercepting.

Keywords: Javascript Front-end JSON Vue.js Ajax

Added by -Zeus- on Tue, 05 Oct 2021 19:07:42 +0300