1. axios 基本特性 axios 官网: https://github.com/axios/axios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 axios.delete('http://localhost:8000/depart/3' , { params: { id: 2 } }).then(function (ret ) { console .log(ret.data) }) axios.put('http://localhost:8000/depart/3' , { params: { id: 2 } }).then(function (ret ) { console .log(ret.data) }) axios.get('http://localhost:8000/depart/' ).then(function (ret ) { console .log(ret.data) })
1.1 GET传递参数
通过 URL 传递参数
通过params 选项传递参数
1 2 3 4 5 6 7 8 9 10 11 12 13 axios.get('http://localhost:8000/depart?id=123' ).then(function (ret ) { console .log(ret.data) }) axios.get('http://localhost:8000/depart' , { params: { id: 2 } }).then(function (ret ) { console .log(ret.data) })
其他传参方式与GET请求无太大差异,请参考上面代码段
2. axios 全局配置
axios.defaults.timeout = 3000; //超时时间
axios.defaults.baseURL = ‘http://localhost:8000/' ; // 默认地址
axios.defaults.headers[‘mytoken’] = ‘123123asdawdaw’ // 设置请求头
3. axios 拦截器 3.1 请求拦截器 在请求发送之前设置一些信息
1 2 3 4 5 6 7 8 axios.interceptors.request.use(function (config ) { config.headers['mytoken' ] = '123123asdawdaw' return config }, function (err ) { return Promise .reject(err) })
3.2 响应拦截器 1 2 3 4 5 6 7 axios.interceptors.response.use(function (res ) { return res; }, function (err ) { return Promise .reject(err) })
4. async/await 的基本用法
async 关键字用于函数上(async函数的返回值是Promise实例对象)
await 关键字用于async函数当中 (await可以得到异步处理的结果)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 async function queryData ( ) { let ret = await axios.get('http://localhost:8000/depart/2' ) console .log(ret) } queryData() async function queryData ( ) { let ret = await axios.get('http://localhost:8000/depart/2' ) return ret } queryData.then(ret => { console .log(ret) })
4.1 async/await 处理多个异步请求 1 2 3 4 5 6 7 8 9 10 11 async function queryData ( ) { let info = await axios.get('http://localhost:8000/depart/2' ) let ret = await axios.get('http://localhost:8000/depart/2' + info.data) return ret } queryData.then(ret => { console .log(ret) })