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里 该方法有三个参数,分别是参数,和两个回调函数,参数就是我 ...
随机推荐
- rookit入門
来源:rootkit_com 作者:Clandestiny 翻译:fqh “Help!我是一名新手!我需要一款rootkit入侵朋友的机器…我想编写自己的rootkit…我想开始开发代码… 该从哪里入 ...
- JUnit中Assert简单介绍
junit中的assert方法全部放在Assert类中,总结一下junit类中assert方法的分类.1.assertTrue/False([String message,]boolean condi ...
- Permission denied
记录在一次启动tomcat时提示:Permission denied 信息. 解释一下Permission denied的意思-没有权限 解决办法: sudo chmod -R 777 某一目录其中- ...
- C语言注意事项
#include <stdio.h> int main() { /*********************************************** * 指针使用注意事项: * ...
- EntityFramework 知识点与sql优化汇总
一.EntityFramework modelBuilder.Entity<Domain.UseOilPlanDetail>().HasRequired(x => x.MainOil ...
- 函数高阶(函数,改变函数this指向,高阶函数,闭包,递归)
一.函数的定义方式 1.函数声明方式 function 关键字(命名函数) 2.函数表达式(匿名函数) 3.new Function( ) var fn = new Function(‘参数1 ...
- Android开发:图文分析 Handler通信机制 的工作原理
前言 在Android开发的多线程应用场景中,Handler机制十分常用 下面,将图文详解 Handler机制 的工作原理 目录 1. 定义 一套 Android 消息传递机制 2. 作用 在多线程的 ...
- redis性能
- 笔记63 Spring Boot快速入门(三)
SpringBoot中使用JSP Springboot的默认视图支持是Thymeleaf,但是Thymeleaf还没开始学,熟悉的还是jsp,所以要让Springboot支持 jsp. 一.在pom. ...
- hive之基本架构
什么是Hive hive是建立在Hadoop体系架构上的一层SQL抽象,使得数据相关人员是用他们最为熟悉的SQL语言就可以进行海量的数据的处理.分析和统计工作,而不是必须掌握JAVA等变成语言和具备开 ...