axios的介绍及使用
特点:支持promise API 、 拦截请求和响应、转换请求数据和响应数据、取消请求、自动转换JSON数据、客户端支持防御XSRF等;
axios请求方法(需后端定义):get获取数据、 post提交数据(用于表单提交和文件上传)、 patch更新(只将修改的数据推送到后端)、 put更新(所有数据都推送到后端)、 delete删除数据
例如:axios_test.vue:
<script>
export default{
name:'axios_test',
components:{},
created(){
//get
axios.get('/data.json',{params:{id:12,name:'zs'}}).then((res)=>{
console.log(res);
})
或:axios({
method:'get',
url:'/data.json',
params:{
id:12,
name:'zs'
}
}).then((res)=>{
console.log(res);
})
//post
axios.post('/xxx').then({
// 默认application/json常用,用于没有上传文件时,用法同上不详写了
// form-data 表单提交(用于文件上传)
let data = { id:12}
let formData = new FormData()
for(let key in data){
formData.append(key,data[key]);
}
axios.post('post',formData).then(res=>{
console.log(res)
})
})
//put/patch
axios.put('/put',data).then(res=>{
console.log(res);
})
//delete
axios.delete('/delete',{ params:{id:12}}).then(res=>{}) //实则底层调用get请求,params数据将添加到url中去;
axios.delete('/delete',{ data:{id:12}}).then(res=>{}) //实则底层调用post请求,data数据将放在请求体中;
//并发请求:同时进行多个请求,并统一处理返回值。 axios.all()和axios.spread()
axios.all([
axios.get('/data.json'),
axios.get('/city.json')
]).then(
axios.spread((dataRes,cityRes)=>{
console.log(dataRes,cityRes);
})
) //创建axios实例
let instance = axios.create({ //设置后会覆盖以前的设置
baseURL:'http://localhost:8080',
timeout:1000,
url:'/data.json',
method:'get/post/put/patch/delete',
headers:{token:''}, //设置请求头
params:{}, //请求参数拼接到url上
data:{} //请求参数放到请求体中
})
let instance2 = axios.create()
instance.get('/data.json').then(res=>{})
//1、axios全局配置
axios.defaults.timeout = 1000;
axios.defaults.baseURL = 'http://localhost:8080'
//2、axios实例配置(常用方式)
let instance = axios.create() //单独创建防止全局污染
instance.defaults.timeout=3000 //单独设置防止覆盖其他设置
//3、axios请求配置 (三种方式中优先级最高)
instance.get('/data.json',{
time:5000
}) //拦截器:在请求或响应被处理前拦截它们,分为请求拦截器和响应拦截器
//请求拦截器
axios.interceptors.request.use(config=>{
//在发送请求前做些什么
return config
},err=>{
//在请求发生错误时怎么处理
return Promise.reject(err)
})
//响应拦截器
axios.interceptors.response.use(config=>{
//请求成功对响应数据做处理
return res
},err=>{
//在响应发生错误时怎么处理
return Promise.reject(err)
})
//取消拦截器(了解)
let interceptor = axios.interceptors.request.use(config=>{
config.headers={ auto:true}
return config
})
axios.interceptors.request.eject(interceptor);
//拦截器例子1:比如微博评论时需要先登录
let instance = axios.create({})
instance.interceptors.request.use(config=>{
config.headers.token = '';
return config
})
//拦截器例子2:移动端开发时的请求等待
let instance_phone = axios.create({})
instance_phone.interceptors.request.use(config=>{
$('#modal').show() // 请求等待弹窗
return config
})
instance_phone.interceptors.response.use(res=>{
$('#modal').hide() // 请求等待弹窗隐藏
return res
})
//错误处理 实际开发中,一般添加统一错误处理,特殊的单独添加。
//添加请求错误处理拦截器
let instance = axios.create({})
instance.interceptors.request(config=>{
return config
},err=>{
//请求错误 一般http状态码以4开头,常见:401超时,404 没找到
$('#modal').show()
setTimeout(()=>{
$('#modal').hide()
},2000)
return Promise.reject(err)
})
//添加响应错误处理拦截器
instance.interceptors.response(res=>{
return res
},err=>{
//响应错误 一般http状态码以5开头,常见:500系统错误,502系统重启
$('#modal').show()
setTimeout(()=>{
$('#modal').hide()
},2000)
return Promise.reject(err)
})
//添加特殊错误处理
instance.get('/data.json').then(res=>{
console.log(res)
}).catch(err=>{
console.log(err)
})
//取消请求(了解)
let source = axios.CancelToken.source()
axios.get('data.json',{cancelToken:source.token}).then()
source.cancel('cancel http') //取消请求(message可选)
比如当用户查询数据耗时太久,用户不再查询进行了其他操作时可能用到,一般用不到。 }
}
</script>
axios实战:移动端UI的vant使用和axios的封装:
①npm i vant
②npm i ts-import-plugin -D
③按照 API文档的快速上手提示,在 babel.config.js 中配置
module.exports = {
plugins: [
['import', {
libraryName: 'vant',
libraryDirectory: 'es',
style: true
}, 'vant']
]
};
④ 引入 Vant 组件
test.vue:
<template>
<van-button type="default">默认按钮</van-button>
</template>
<script>
import axios from 'axios'
import {Button} from 'vant'
export default {
name:'showlist',
components:{
[Button.name]=Button //局部注册,template模板中没有引用时可不写,vant官方格式。
},
created(){
axios.get(./data.json).then((res)=>{
console.log(res)
})
}
}
</script>
⑤ router.js中添加一条路由:{path:'/showlist',name:'',component:()=>import('./views/showlist.vue')}
⑥ npm run serve 启动服务测试
axios的封装 示例
①contactApi.js:
const CONTACT_API = {
//获取联系人列表
getContactList:{
method:'get',
url:'/contactList'
},
//新建联系人 form-data
newContactForm:{
method:'post',
url:'/contact/new/form-data'
},
//新建联系人 application/json
newContactJson:{
method:'post',
url:'/contact/new/json'
},
//编辑联系人
editContact:{
method:'put',
url:'/contact/edit'
},
//删除联系人
delContact:{
method:'delete',
url:'/contact'
},
}
export default CONTACT_API
②http.js:
import axios from 'axios'
import service from './contactApi.js'
import {Toast} from 'vant'
//service循环遍历,输出不同的请求方法
let instance = axios.create({
baseURL:'http://localhost:9000/api',
timeout:1000
})
const Http = {}; //存放请求方法的容器
for(let key in service){
let api = service[key]; //url、method
Http[key] = async function(
params, //请求参数
isFormData = false, //标识是否是form-data请求
config={} //配置参数
){
let newParams = {}
if(params && isFormData){
newParams = new FormData()
for(let i in params){
newParams.append(i,params([i]))
}
}else{
newParams = params
}
//不同请求的判断
let response = {}; //请求的返回值
if(api.method ==='put'|| api.method ==='post'||api.method==='patch'){
try{ response = await instance[api.method](api.url,newParams,config)
}catch(err){
response = err
}
}else if(api.method ==='delete'||api.method==='get'){
config.params = newParams
try{
response = await instance
[api.method](api.url,config)
}catch(err){
response = err
}
}
return response;
}
}
//拦截器的添加
instance.interceptors.request.use(config=>{
Toast.loading({
mask:false, //是否有阴影
duration:0, //一直存在
forbidClick:true, //禁止点击
message:'加载中...'
})
return config
},err=>{
Toast.clear()
Toast('请求错误,请稍后重试')
})
//响应拦截器
instance.interceptors.response.use(res=>{
Toast.clear()
return res.data
},()=>{
Toast.clear()
Toast('请求错误,请稍后重试')
})
export default Http
③main.js文件中引入http.js,并将其挂载到vue实例上,引入后添加如下:
Vue.prototype.$http = Http;
④vue组件中使用:
<script>
import axios from 'axios'
import {Button} from 'vant'
export default {
name:'showlist',
components:{
[Button.name]=Button //局部注册,template模板中没有引用时可不写。
},
methods:{
//获取联系人列表
async getList(){
let res = await this.$http.getContact()
this.list = res.data
}
}
}
</script>
axios的介绍及使用的更多相关文章
- axios基础介绍
axios基础介绍 get请求要在params中定义,post要在data中定义.
- 学习axios必知必会(1)~axios基本介绍、axios配置、json-server接口模拟工具
一.axios基本介绍 1.axios(前端最流行的 ajax 请求库) 特点: ① 基于 xhr + promise 的异步 ajax 请求库 ② 浏览器端/node 端都可以使用 ③ 支持请求/响 ...
- 3-2 axios基础介绍
1.静态引用 <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 2.npm ...
- axios简单介绍
axios的配置,get,post,axiso的同步问题解决 一.缘由 vue-resoure不更新维护,vue团队建议使用axios. 二.axios安装 1.利用npm安装npm install ...
- axios Api介绍
1.Performing a GET request axios.get('/user?ID=12345') .then(function (response) { // handle success ...
- Vuex与axios介绍
Vuex集中式状态管理里架构 axios (Ajax) Vuex集中式状态管理架构 -简单介绍: vuex是一个专门为Vue.js设计的集中式状态管理架构. 我们把它理解为在data中需要共享给其他组 ...
- 介绍axios和promise
今天小编为大家带来 axios 和promise的详细讲解,包含 axios的使用方法 多种写法,封装 以及 promise的详细讲解,项目中如何运用等,会一一的为大家讲解清楚. 一.axios的介绍 ...
- 4.npm模块安装和使用(axios异步请求,lodash工具库)
建立package.json npm init 下载包 npm install axios npm install lodash 下载包,并加到package里面 npm install axios ...
- 使用axios实现上传视频进度条
这是最终的效果图 先介绍一下axios的使用:中文的axios官方介绍 首先定义一个uploadTest方法,写在vue文件的methods里 该方法有三个参数,分别是参数,和两个回调函数,参数就是我 ...
随机推荐
- UVALive 4794 Sharing Chocolate
Sharing Chocolate Chocolate in its many forms is enjoyed by millions of people around the world ever ...
- 三、hibernate中持久化类的使用
hibernate的持久化类 持久化:将内存中的一个对象持久化到数据库中的过程,hibernate就是一个用来进行持久化的框架 持久化类:一个Java对象与数据库中表建立了关系映射,那么这个类在hib ...
- java nio socket实例
Server端代码: public class NioServer { //通道管理器 private Selector selector; //获取一个ServerSocket通道,并初始化通道 p ...
- windows 之间远程大文件传输问题解决
今天我在远程登录另一台windows的时候,需要传输一个大约3GB的文件,但是每每经过了一会儿,就会提示我未知错误问题. 我在网上找了一下,本问题的解决方法如下. 1.打开远程登录的对话窗口 2.选择 ...
- BZOJ 4289 最短路+优化建图
题意:给出一个N个点M条边的无向图,经过一个点的代价是进入和离开这个点的两条边的边权的较大值,求从起点1到点N的最小代价.起点的代价是离开起点的边的边权,终点的代价是进入终点的边的边权. 解法:参考h ...
- 牛客练习赛48 C,D,E
C 小w的糖果 题意:3种操作,第一种是使pos右边的数全部+1,第二种是pos右边的数依次+k(k从1开始递增),第三种是pos右边的数依次+k^2(k从1开始递增). 解法:第一种我们很容易想到差 ...
- MySQL中可能遇到的问题及解决方法
一.在创建存储函数时,出现错误: ERROR 1418 (HY000): This function has none of DETERMINISTIC, NO SQL, or READS SQLDA ...
- Shiro学习(2)身份验证
身份验证,即在应用中谁能证明他就是他本人.一般提供如他们的身份ID一些标识信息来表明他就是他本人,如提供身份证,用户名/密码来证明. 在shiro中,用户需要提供principals (身份)和cre ...
- [bzoj1706]奶牛接力跑 题解 (矩阵快速幂(或者叫倍增Floyd?))
Description FJ的N(2 <= N <= 1,000,000)头奶牛选择了接力跑作为她们的日常锻炼项目.至于进行接力跑的地点 自然是在牧场中现有的T(2 <= T < ...
- 12.RabbitMQ多机集群
配置两台Linux CentOS 6.7虚拟主机 CentOS6.7下载地址 https://pan.baidu.com/s/1i5GPg9n 安装视频下载 https://pan.baidu.c ...