一、axios基础用法
-
基于promise用于浏览器和node.js的http客户端
-
支持浏览器和node.js
-
支持promise
-
能拦截请求和响应
-
自动转换JSON数据
-
能转换请求和响应数据
-
get和 delete请求传递参数
-
通过传统的url 以 ? 的形式传递参数
-
restful 形式传递参数
-
通过params 形式传递参数
-
post 和 put 请求传递参数
-
通过选项传递参数
-
通过 URLSearchParams 传递参数
二、axio 传参
1.发送get 请求
axios.get('http://localhost:3000/adata').then(function(ret){
// 拿到 ret 是一个对象 所有的对象都存在 ret 的data 属性里面
// 注意data属性是固定的用法,用于获取后台的实际数据
// console.log(ret.data)
console.log(ret)
})
- get 请求传递参数
// 通过传统的url 以 ? 的形式传递参数
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
})
// restful 形式传递参数
axios.get('http://localhost:3000/axios/123').then(function(ret){
console.log(ret.data)
})
// 通过params 形式传递参数
axios.get('http://localhost:3000/axios', {
params: {
id: 789
}
}).then(function(ret){
console.log(ret.data)
})
3.axios 的 post 请求
// 通过选项传递参数
axios.post('http://localhost:3000/axios', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
// 通过 URLSearchParams 传递参数
var params = new URLSearchParams();
params.append('uname', 'zhangsan');
params.append('pwd', '111');
axios.post('http://localhost:3000/axios', params).then(function(ret){
console.log(ret.data)
})
4.axios put 请求传参 和 post 请求一样
axios.put('http://localhost:3000/axios/123', {
uname: 'lisi',
pwd: 123
}).then(function(ret){
console.log(ret.data)
})
5axios delete 请求传参 传参的形式和 get 请求一样
axios.delete('http://localhost:3000/axios', {
params: {
id: 111
}
}).then(function(ret){
console.log(ret.data)
})
三、axios 全局配置
- 配置公共的请求网址
axios.defaults.baseURL = ‘https://api.example.com’;
配置 超时时间
axios.defaults.timeout = 2500;
配置公共的请求头
axios.defaults.headers.common[‘Authorization’] = AUTH_TOKEN;
配置公共的 post 的 Content-Type
axios.defaults.headers.post[‘Content-Type’] = ‘application/x-www-form-urlencoded’;
四 async await
- async作为一个关键字放到函数前面
- 任何一个
async
函数都会隐式返回一个promise
await
关键字只能在使用async
定义的函数中使用- await后面可以直接跟一个 Promise实例对象
- await函数不能单独使用
五、处理多个异步请求
async function queryData() {
// 添加await之后 当前的await 返回结果之后才会执行后面的代码
var info = await axios.get('async1');
// 让异步代码看起来、表现起来更像同步代码
var ret = await axios.get('async2?info=' + info.data);
return ret.data;
}
queryData().then(function(data){
console.log(data)
})