The basic usage and characteristics of axios are not explained
The Chinese document is as follows
1. Install
axios installation
npm or yarn
npm install axios
yarn add axios
or use cdn
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
qs installation (recommended)
npm
npm install qs
or use cdn
<script src="https://cdn.bootcdn.net/ajax/libs/qs/6.9.4/qs.min.js"></script>
hint
qs.parse()和qs.stringify()
这两种方法虽然都是序列化,但是还是有区别的。
qs.parse()是将URL解析成对象的形式
qs.stringify()是将对象 序列化成URL的形式,以&进行拼接
2. Introduce
Generally, axios is packaged in the project
<template>
...
</template>
<script>
// axios引入
import axios from 'axios'
// qs引入(建议)
import qs from 'qs'
export default {
...
}
</script>
3. use
The following code does not configure a failure callback
.catch(error => { //失败回调 console.log(error); })
GETSend request
A request without parameters defaults to GET
axios({
url: 'url',
}).then(res => {
console.log(res)
})
request with parameters
axios({
url: 'url?id=1&type=2',
method: 'get',
}).then(res => {
console.log(res)
})
Send request with params
axios({
url: 'url',
method: 'get',
params: {id: 1}
}).then(res => {
console.log(res)
})
POSTSend request
POST request parameters will be automatically converted into JSON format. If form format is required, it can be converted by qs serialization tool
No parameter request
axios({
url: 'url',
method: 'post',
}).then(res => {
console.log(res)
})
request with parameters
axios.post('接口地址',{
id:'1',
type:2
}).then(res=>{
console.log(res);
})
Send request using data
let _data = {
id : '1',
type : 2
}
axios({
url: 'url;',
method: 'post',
data: _data
}).then(res => {
console.log(res)
})
Use URLSearchParams to pass parameters to send requests
let params = new URISearlhParams();
params.append('id','1');
params.append('type', 2);
axios.post('url',params).then(res =>{
console.log(res)
})
Use qs to send form type data
axios({
url: 'url',
method: 'post',
data: qs.stringify({
id : '1',
type : 2
}),
headers: {
// 不加也行
'Content-Type': 'application/x-www-form-urlencoded',
},
}).then(res => {
console.log(res)
})