致访客
感谢各位一年多的陪伴,因内容调整,本站将于近日迁移到新域名并不再更新主要内容。

MENU

Why does Vue abandon the classic Ajax and choose the new technology Axios?

• February 11, 2022 • π

致访客
感谢各位一年多的陪伴,因内容调整,本站将于近日迁移到新域名并不再更新主要内容。
特此通知。
  1. What network module to choose?
    There are many ways to send network requests. Here's a brief introduction:
  2. Traditional Ajax is based on XMLHttpRequest (XHR)
  3. jQuery - Ajax

Why not use jQuery's Ajax?

There is no need to use jQuery in vue development, because jQuery is very heavyweight.

  1. Vue officially launched Vue-resource in Vue1.x.

Vue-resource corner jQuery is much lighter, but after vue2.x, You Yuxi no longer maintains Vue-resource, in short, it is deprecated.

  1. You Yuxi recommends using axios.
  2. Features of axios
    Send XMLHttpRequest request in browser

send http request in node.js
Promise API support
Support for intercepting requests and responses
Transform request and response data

  1. Axios supports multiple request methods
    axios(config)

axios.request(config)
axios.get(url,[,config])
axios.delete(url,[,config])
axios.head(url,[,config])
axios.post(url,[,data[, config]])
axios.put(url,[,data[, config]])
axios.patch(url,[,data[, config]])
Fourth, send concurrent requests
Sometimes, multiple requests are sent at the same time.

Using axios.all, you can put an array of multiple requests.

Axios.all([]) returns an array. Using axios.spread, the array [res1, res2] can be expanded into res1 and res2.

import axios from 'axios'

export default {

name: 'app',
created(){
    axios.all([axios.get('http://127.0.0.1:8080/getUserList'),
                axios.get('http://127.0.0.1:8080/getUserPage',{
                    params: {pageNum: 1, pageSize: 10}
                })
    ]).then(axios.spread((res1,res2) => {
        console.log(res1)
        console.log(res2)
    }))
}

}

  1. Global configuration
  2. axios from 'axios'

export default {

name: 'app',
created(){

    axios.defaults.baseURL = 'http://127.0.0.1:8080'
    
    axios.all([axios.get('/getUserList'),
                axios.get('/getUserPage',{
                    params: {pageNum: 1, pageSize: 10}
                })
    ]).then(axios.spread((res1,res2) => {
        console.log(res1)
        console.log(res2)
    }))
}

}

  1. Create axios instance
  2. instance1 = axios.create({

baseURL: 'http://127.0.0.1:8080',
timeout: 5000
})

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

instance1({
url: '/home/getUserPage',
params: {

type: 'pop',
page: 1

}
}).then(res => {
console.log(res);
})

const instance2 = axios.create({
baseURL: 'http://127.0.0.1:8081',
timeout: 10000,
// headers: {}
})

Seven, common configuration options

  1. Request address

url:'http://127.0.0.1:8080/getUserList'

  1. Request type

method:'get'

  1. Request path

baseURL:'http://127.0.0.1:8080'

  1. Data processing before request

transformRequest:[function(data){}],

  1. Data processing after request

transformResponse: [function(data){}],

  1. Custom request headers

headers:{'x-Requested-With':'XMLHttpRequest'},

  1. URL query object

params:{ id: 1 },

  1. Query object serialization function

paramsSerializer: function(params){ }

  1. request body

data: { key: 'aa'},

  1. Timeout setting s

timeout: 5000,

  1. Whether cross-domain with Token

withCredentials: false,

  1. Custom request processing

adapter: function(resolve, reject, config){},

  1. Authentication information

auth: { uname: '', pwd: '12'},

  1. The data format of the response is json / blob / document / arraybuffer / text / stream

responseType: 'json',

Eight, axios package
import axios from 'axios'

export default function axios(option){

return new Promise((resolve,reject) => {

    const instance = axios.create({
        url: 'api',
        timeout: 5000,
        headers: ''
    })
    instance(option).then(res => {
        resolve(res)
    }).catch(err => {
        reject(err)
    })
})

}

Nine, encapsulate a request function

  1. Pass in the callback function
  2. function request(config, success, failure) {

const instance = axios.create({

baseURL: 'http://127.0.0.1:8080',
timeout: 5000

})

instance(config)

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

}

Call the packaged request module

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

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

  1. Pass in a parameter for callback
  2. function request(config) {

const instance = axios.create({

baseURL: 'http://127.0.0.1:8080',
timeout: 5000

})

instance(config.baseConfig)

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

}

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

request({
baseConfig: {

},
success: function (res) {

},
failure: function (err) {

}
})

  1. Promise usage
  2. function request(config) {

return new Promise((resolve, reject) => {

const instance = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 5000
})
instance(config)
  .then(res => {
    resolve(res)
  })
  .catch(err => {
    reject(err)
  })

})
}

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

  1. Simplify Promises
  2. function request(config) {

return new Promise((resolve, reject) => {

const instance = axios.create({
  baseURL: 'http://127.0.0.1:8080',
  timeout: 5000
})
return instance(config)

})
}

  1. Interceptor in axios
    What is 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
Certain network requests (such as login (token)), must carry some special information
import axios from 'axios'

export function request(config) {

const instance = axios.create({

baseURL: 'http://127.0.0.1:8080',
timeout: 5000

})

instance.interceptors.request.use(config => {

// console.log(config);
return config

}, err => {

// console.log(err);

})

instance.interceptors.response.use(res => {

// console.log(res);
return res.data

}, err => {

console.log(err);

})

return instance(config)