axios network request

1. Install axios dependencies

npm install axios --save

2. Import axios

import axios from 'axios'

3. Basic usage

1. No parameters are passed (the default is get request)
axios({
  url: 'http://httpbin.org/get',
  method:'get'//Can be omitted if not written, the default is get
}).then(res => {
  console.log(res);
})
2. Do not pass parameters (the second way of writing)
axios.get('http://httpbin.org/get').then(res => {
 console.log(res);
})
3. Passing parameters (the first way of writing)
axios({
 url:'http://httpbin.org/get?type=sell&id=1'
}).then(res => {
 console.log(res);
})
4. Passing parameters (the second way of writing)
axios({
 url:'http://httpbin.org/get',
 params:{//Parameter splicing specifically for get requests
  type:'sell',
  id:1
 }
}).then(res => {
 console.log(res);
})

Because it supports Promise, you can get the return result directly by using then

Note: If it is a get request, use params to pass parameters, if it is a post request, you need to use data

Fourth, axios concurrent requests

Description: Send two requests, both of which are executed after they arrive.

Use axios.all([axios(),axios(),axios()]).then()

axios.all([axios({
  url: 'http://httpbin.org/get'
}), axios({
  url: 'http://httpbin.org/get',
  params: {//Parameter splicing specifically for get requests
    type: 'sell',
    id: 1
  }
})]).then(results => {
  console.info(results)//get is a data
})

The result obtained directly by then() is data, and use axios.spread to get the return result of each request

axios.all([axios({
  url: 'http://httpbin.org/get'
}), axios({
  url: 'http://httpbin.org/get',
  params: {//Parameter splicing specifically for get requests
    type: 'sell',
    id: 1
  }
})]).then(axios.spread((res1,res2)=>{
  console.log(res1);
  console.log(res2);
}))

Five, axios global configuration

//After the global configuration is completed, you can directly write the request method name when requesting
axios.defaults.baseURL='http://httpbin.org/'  

axios.defaults.timeout=5000

It can only deal with the server in the same address. If the requested data is not in the same server, it is not appropriate to use the global configuration. (For example: the home page data is on one server, and the list data is on another server), then create the corresponding axios instance

6. Create the corresponding axios instance

There are multiple requests in the first server address. If there is only one request, just write an address directly. There is no need to create an instance.

const instance1 = axios.create({
  baseURL: 'http://httpbin.org/',
  timeout: 5000
})

instance1({
  url: '/home'
}).then(res => {
  console.log(res);
})

instance1({
  url: '/list'
}).then(res => {
  console.log(res);
})

The second server address, after creating an axios instance

const instance2 = axios.create({
  baseURL: 'http://192.168.1.1',
  timeout: 6000
})
instance2({
  url: '/list'
}).then(res => {
  console.log(res);
})

Seven, axios network packaging

Create a network folder under the src folder and create a request.js

export function can export multiple in it, if export default is used, only one can be exported

1. The first writing method (callback function method)
import axios from "axios"
/**
 * 
 * @param {request address} config 
 * @param {request success} success 
 * @param {request failed} failure 
 */
export function request(config, success, failure) {
    //1. Create axios instance
    const instance = axios.create({
        baseURL: 'http://httpbin.org',
        timeout: 5000
    })

    //2. Send a real network request
    instance(config).then(res => {
        success(res)
    }).catch(err => {
        failure(err)
    }) 
}

call on page

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

request({
  url: 'get'
}, res => {
  console.log(res);
}, err => {
  console.log(err);
})
2. The second writing method (callback function method)
import axios from "axios"
/**
 * 
 * @param {config It is an object, when it is passed in, everything needed is put into config} config 
 */
export function request(config) {
    //1. Create axios instance
    const instance = axios.create({
        baseURL: 'http://httpbin.org',
        timeout: 5000
    })

    //2. Send a real network request
    instance(config.baseConfig).then(res => {
        config.success(res)
    }).catch(err => {
        config.failure(err)
    })
}

call on page

request({  baseConfig: {  },  success: function (res) {  },  failure: function (err) {  }})
3. The third way of writing (Promise)
import axios from "axios"
/**
 *  Promise Way
 * @param {*} config 
 * @returns 
 */
export function request(config) {
    return new Promise((resolve, reject) => {
        //1. Create axios instance
        const instance = axios.create({
            baseURL: 'http://httpbin.org',
            timeout: 5000
        })

        //2. Send a real network request
        instance(config)
            .then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
    })
}

call on page

request({
  url:'get'
}).then(res=>{
    console.log(res);
}).catch(err=>{
    console.error(err);
})
4. The fourth way of writing (Promise) is recommended
import axios from "axios"

export function request(config) {
     //1. Create axios instance
     const instance = axios.create({
        baseURL: 'http://httpbin.org',
        timeout: 5000
    })

    //2. Sending a real network request instance itself returns a Promise
     return instance(config)  
}

call on page

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

Eight, axios interceptor use

Why do request interception, the role of request interception:

  • For example, some information in config does not meet the requirements of the server
  • For example, every time you send a network request, you want to display a requested icon in the interface
  • Some network requests must carry some special information (for example, login needs to carry a token)

Four cases:

  • request succeeded
  • Request failed
  • Response succeeded
  • response failed

axios.interceptors intercept global

instance.interceptors intercepts the instance created

instance.interceptors.request.use() request interception (pass two functions, one request succeeds and one request fails)

instance.interceptors.response.use() Response interception (pass two functions, one responds successfully and one fails)

After interception, you must return out, otherwise you will not be able to get the data later

import axios from "axios"

/**
 * Interceptor use
 * @param {*} config 
 * @returns 
 */
export function request(config) {
    //1. Create axios instance
    const instance = axios.create({
        baseURL: 'http://httpbin.org',
        timeout: 5000
    })

    //2.axios interceptor
    //axios.interceptors //This way of writing is to intercept the global
    //instance.interceptors intercepts the instance created
    //request.use() intercepts the request and passes two functions, one request succeeds and one fails
    instance.interceptors.request.use(config => {
        //Why do request interception, the role of request interception
        //1. For example, some information in config does not meet the requirements of the server

        //2. For example, every time you send a network request, you want to display a requested icon in the interface

        //3. Some network requests must carry some special information (for example, login needs to carry a token)
        console.log(config);
        return config //It must be return ed, otherwise the data will not be available later
    }, err => {
        console.log(err);
    });

    //Response interception
    instance.interceptors.response.use(res => {
        console.log(res);
        return res;//It must be return ed, otherwise the data will not be available later
    }, err => {
        console.log(err);
    });

    //3. Send a real network request
    return instance(config)
}

Tags: Javascript Vue.js Vue Front-end

Posted by George Botley on Thu, 02 Jun 2022 08:23:38 +0530