<!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将表单以对象的形式传输
