axios学习和使用
其他
2019-10-21 23:17:31
阅读次数: 0
网络请求的方式
- 传统的Ajax,基于XMLHttpRequest(不推荐)
- jQuery-Ajax (在vue开发中不推荐)
- 相对于传统的Ajax非常好用
- 但是jQuery的代码1w行,vue的代码1w行,在vue开发中,完全没有为了用网络请求就引用一个重量级的框架
- axios(推荐)
- 在Vue-resource停止更新之后,axios是vue作者推荐的一款轻便的基于 promise 的 HTTP 库
认识Axios
- 可以理解为 ajax i/o system 的缩写
- 功能特点:
- 在浏览器中发送 XMLHttpRequests 请求
- 在 node.js 中发送 http请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 。。。
- 支持多种请求方式:
- axios(config)
- axios.request(config)
- axios.get(url[, config])
- axios.delete(url[, config])
- axios.head(url[, config])
- axios.put(url[, data[, config]])
- axios.patch(url[, data[, config]])
发送基本请求
**发送get请求演示**
import axios from 'axios'
export default {
name:'app',
created(){ //在vue的生命周期函数中
//提问:为什么没有跨域的问题?
//1.没有请求参数
axios.get('http://123.207.32.32:8000/api/v1')
.then(res=>{
console.log(res);
}).catch(err=>{
console.log(err)
})
//2.有参数
axios.get('http://123.207.32.32:8000/api/v1',
{params:{type:'sell',page:1}})
.then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
}
}
**发送并发请求**
created(){ //在vue的生命周期函数中
axios.all([axios.get('http://123.207.32.32:8000/api'),
axios.get('http://123.207.32.32:8000/api')],
{params:{type:'sell',page:1}})
.then(axios.spread((res1,res2)=>{
console.log(res1);
console.log(res2);
}))
}
全局配置
- 在开发中可能很多参数都是固定的,这个时候我们可以进行一些抽取, 也可以利用axiox的全局配置
//提取全局的配置
axios.defaults.baseURL = 'http://123.207.32.32:8000'
//发送并请求
axios.all([axios.get('/api'),
axios.get('/home'),
{params:{type:'sell',page:1}}])
.then(axios.spread((res1,res2)={
console.log(res1);
console.log(res2);
}))
- 常见的全局配置
- 1.请求地址:url: '/user' 2.请求类型:method: 'get',
- 3.请根路径:baseURL: 'http://www.mt.com/api' 4.请求前的数据处理:transformRequest:[function(data){}],
- 5.请求后的数据处理:transformResponse: [function(data){}] 6.自定义的请求头:headers:{'x-Requested-With':'XMLHttpRequest'},
- 7.URL查询对象:params:{ id: 12 } 8.查询对象序列化函数:paramsSerializer: function(params){ }
- 9.request body:data: { key: 'aa'} 10.超时设置s:timeout: 1000,
- 11.跨域是否带Token:withCredentials: false 12.自定义请求处理:adapter: function(resolve, reject, config){},
- 13.身份验证信息:auth: { uname: '', pwd: '12'} 14.响应的数据格式 json / blob /document /arraybuffer / text / stream:responseType: 'json',
axios的实例
- 为什么要创建axios的实例呢?
- 当给该实例设置一些默认配置时, 这些配置就被固定下来了.但是后续开发中, 某些配置可能会不太一样.
- 这个时候, 我们就可以创建新的实例, 并且传入属于该实例的配置信息.
//创建新的实例
const axiosInstance =axios.create({
baseURL:'http://123.207.32.32:8000',
timeout:5000,
headers:{
'Content-Type':'application/x-www.from-urlencoded'
}
//发送网络请求
axiosInstance({
url:'/api',
method:'get',
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
})
axios封装
//创建的axios文件中
import originAxios from 'axios'
export default function axios(option){
return new Promise((resolve,reject)={
//1.创建axios实例
const instance = originAxios.create({
baseURL:'/api',
timeout:5000,
headers:''
});
//2.传入的对象进行网络请求(optiond)
instance(option).then(res=>{
resolve(res);
}).catch(err=>{
reject(err);
})
//对第二步的简写(因为axios本身返回的就是一个Promise)
//去掉export下面return Promise的那一行
return instance(config)
})
}
Axios拦截器
- axios提供了拦截器,用于我们在发送每次请求或者得到相应后,进行对应的处理
**请求拦截**
instance.interceptors.request.use(config=>{
console.log('来到了request拦截的success中')
// 1.当发送网络请求时,在页面中添加了一个loading组件,作为动画
// 2. 某些请求要求用户必须登陆,判断用户是否有token,如果没有token跳转到login页面
// 3.对请求的参数进行序列化
config.data =qs.stringify(config.data)
console.log(config)
//当拦截完了一定要记得将拦截返回
return config
})
use()中还有一个err参数,表示请求错误后的拦截,请求拦截中错误拦截比较少,通常都是配置相关的拦截,可能的错误比如请求超时时,可以将页面跳转到一个错误的页面中
**响应拦截**
响应的成功拦截中,主要是对数据进行过滤
instance.interceptors.response.use(response=>{
console.log("来到了response拦截success中");
return response.data
响应失败的拦截中,可以根据status判断报错的错误码,跳转到不同的错误提示页面
},err => {
console.log('来到了response拦截的failure中')
if( err && err.response){
switch(err.response.status){
case 400:
err.message = '请求错误',
break;
case 401:
err.message = '未授权的访问',
break;
}
}
return err
})
转载自www.cnblogs.com/JCDXH/p/11716959.html