<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<meta charset="UTF-8">
<title>測試</title>
<script>
// TODO axios發送請求統一模板
axios({
method: `get`, // http請求方法
url: `http://httpbin.org/get?param=hello` // http服務地址
})
.then(function (response) { // 自動轉換JSON數據
// 請求成功響應結果response
console.log(response);
console.log(JSON.stringify(response.url));
}).catch(function (error) {
// 請求異常響應結果
console.log(error);
});
// TODO axios發送GET請求
axios.get("http://httpbin.org/get?param=hello")
.then(function (response){
console.log("[GET] response" + response)
})
.catch(function () {
console.log("[GET] response" + response)
});
/*
使用axios(config)發送http請求,config為該請求的配置信息對象
axios.get等同於axios使用method:get。
axios是基於Promise的HTTP客戶端,所以可以使用then、catch對請求結果進行處理。
* */
// TODO axios通過params包裝發送GET請求
axios.get("http://httpbin.org/get", {
params: {
param: "hello"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
// TODO axios發送POST請求
axios({
method: `post`, // 請求方法
url: `http://httpbin.org/post`, // 請求服務地址
data: {
firstName: 'zz',
lastName: 'wang'
}
});
// TODO axios發送POST請求
axios.post('http://httpbin.org/post', {
firstName: 'zz',
lastName: 'wang'
})
// dismiss [then][catch]
// TODO axios發送並行請求
// 在一些情況下需要某些異步網絡請求結果處理有一定的順序
// 比如 getHello()和getWorld()兩個異步操作,將兩個HTTP的請求都完成之后,結果合並並處理或進行下一步操作
function getHello() {
return axios.get('http://httpbin.org/get?param=hello');
}
function getWorld() {
return axios.get('http://httpbin.org/get?param=world');
}
axios.all([getHello(), getWorld()])
.then(axios.spread(function (res1, res2) {
// 兩個請求都執行完成之后,進入該函數
console.log(res1.data.args.param + " " + res2.data.args.param);
}));
/**
* 上面的axios.all函數還可以寫成如下的形式,返回值是一個數組。
* 然后通過數組下標獲取響應結果數據。results[0]代表第一個getHello()函數的請求結果,
* results[1]代表第二個getWorld()函數的請求結果。
* */
axios.all([getHello(), getWorld()])
.then(function (results) {
console.log(results[0].data.args.param + " " + results[1].data.args.param)
});
</script>
<style>
</style>
</head>
<body>
</body>
Axios將表單以對象的形式傳輸
