1、Axios
1.1、什么是Axios?
Axios是专注于网络数据请求的库。相比于原生的XML HttpRequest对象,axios 更简单易用,相比于jQuery,axios 更加轻量化,只专注于网络数据请求
在服务端它使用原生 node.js http
模块,而在客户端 (浏览端) 则使用 XMLHttpRequests
1.2、Axios发送GET请求
具体语法:axios.get(url[, config])
<button type="button" class="btn btn-primary">GET请求</button>
<script>
document.querySelector("button").addEventListener("click", () => {
axios.get("http://localhost:8088/api/getUser", { params: { name: "晓琳", age: 22 } }).then(resp => {
console.log(resp.data)
})
})
</script>
1.3、Axios发送POST请求
具体语法:axios.post(url[, data[, config]])
<button type="button" class="btn btn-info">POST请求</button>
<script>
document.querySelector("button").addEventListener("click", () => {
axios.post("http://localhost:8088/api/addUser", { name: "小白", age: 25 }).then(resp => {
console.log(resp.data)
})
})
</script>
1.4、Axios发送请求
具体语法:`axios({
url: “请求URL地址”,
method: “请求方式”,
data: { /* POST数据 */ },
params: { /* GET参数 */ }
}).then(callback)`
<button type="button" class="btn btn-warning">Axios</button>
<script>
document.querySelector("button").addEventListener("click", () => {
axios({
url: "http://localhost:8088/api/addUser",
method: "POST",
data: {
name: "小赵",
age: 23
},
}).then(resp => {
console.log(resp.data)
})
})
</script>
1.5、默认配置
<script>
// 基本路径
axios.defaults.baseURL = 'http://localhost:8088'
// 超时时间
axios.defaults.timeout = 3000
document.querySelector("button").addEventListener("click", () => {
axios({
url: "/api/addUser",
method: "POST",
data: {
address: "河南",
location: "洛阳市"
},
// 请求头
headers: { 'token': 'ASK' },
// 文件上传处理进度事件
onUploadProgress: function (e) {
// console.log(e)
if (e.event.lengthComputable) {
// ...
}
}
}).then(resp => {
console.log(resp.data)
})
})
</script>