• 【前端指南】Axios框架与应用


    Axios 简介

    • axios框架全称 --Ajax-I/O-system
      • 基于promise用于浏览器和node.js的http客户端,因此可以使用Promise API

    axios

    实现Ajax的方式有多种,jQuery封装Ajax,原生XMLHTTPRequest,以及axios,各种方式都有利弊

    • 原生的XMLHTTPRequest的配置和调用方式都很繁琐,实现异步请求十分麻烦
    • jQuery的Ajax相对于原生的Ajax是非常好用的,但是没有必要因为要用Ajax一部网络请求而引用jQuery框架
    Axios
    • 这不是一种新技术,本质上还是对原生XMLHTTPRequest的封装,可用于浏览器和node.js的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范,具备以下特点:
      • 在浏览器中创建XMLHttpRequest请求
      • 在node.js中发送http请求
      • 支持Promise API
      • 拦截请求和响应
      • 转换请求和响应数据
      • 取消要求
      • 自动转换JSON数据
      • 客户端支持方式CSRF/XSRF-跨域请求伪造

    Axios请求的方式

    axios可以请求的方法
    • get:获取数据,请求指定的信息,返回实体数据
    • post:向指定资源提交数据-例如表单提交或文件上传
    • put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
    • patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
    • delete:请求服务器删除指定的数据
    get
    this.$axios({
    		method: 'get',
    		url: '/goods.json',
        	params: {
                id:1
            }
    	}).then(res=>{
    		console.log(res.data);
    	},err=>{
    		console.log(err);
    	})
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    post
    • post请求一般分为两种类型
      1. form-data表单提交,图片上传时用该类型比较多
      2. application/json一般用于Ajax异步请求
    $axios({
    	method: 'post',
    	url: '/url',
    	data: {
    		id:1
    	}
    }).then(res=>{
    	console.log(res.data);
    },err=>{
    	console.log(err);
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    form-data

    let data = {
    	//请求参数
    }
    
    let formdata = new FormData();
    for(let key in data){
    	formdata.append(key,data[key]);
    }
    
    this.$axios.post('/goods.json',formdata).then(res=>{
    	console.log(res.data);
    },err=>{
    	console.log(err);
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    put与patch

    put

    this.$axios.put('/url',{
    				id:1
    			}).then(res=>{
    				console.log(res.data);
    			})
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    patch

    this.$axios.patch('/url',{
    				id:1
    			}).then(res=>{
    				console.log(res.data);
    			})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    delete

    参数以明文形式提交

    this.$axios.delete('/url',{
    				params: {
    					id:1
    				}
    			}).then(res=>{
    				console.log(res.data);
    			})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    参数以封装对象的形式提交

    this.$axios.delete('/url',{
    				data: {
    					id:1
    				}
    			}).then(res=>{
    				console.log(res.data);
    			})
    
    //方法二
    axios({
        method: 'delete',
        url: '/url',
        params: { id:1 }, //以明文方式提交参数
        data: { id:1 } //以封装对象方式提交参数
    }).then(res=>{
    	console.log(res.data);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    并发请求
    • 同时进行多个请求,并统一处理返回值
     this.$axios.all([
    	this.$axios.get('/goods.json'),
    	this.$axios.get('/classify.json')
    ]).then(
    	this.$axios.spread((goodsRes,classifyRes)=>{
    		console.log(goodsRes.data);
    		console.log(classifyRes.data);
    	})
    )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    Axios实例

    创建axios实例
    let instance = this.$axios.create({
    				baseURL: 'http://localhost:9090',
    				timeout: 2000
    			})
    			
    instance.get('/goods.json').then(res=>{
    	console.log(res.data);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • axios实例常用配置:
      • baseURL 请求的域名,基本地址,类型:String
      • timeout 请求超时时长,单位ms,类型:Number
      • url 请求路径,类型:String
      • method 请求方法,类型:String
      • headers 设置请求头,类型:Object
      • params 请求参数,将参数拼接在URL上,类型:Object
      • data 请求参数,将参数放到请求体中,类型:Object
    axios全局配置
    //配置全局的超时时长
    this.$axios.defaults.timeout = 2000;
    //配置全局的基本URL
    this.$axios.defaults.baseURL = 'http://localhost:8080';
    
    • 1
    • 2
    • 3
    • 4
    axios实例配置
    let instance = this.$axios.create();
    instance.defaults.timeout = 3000;
    
    • 1
    • 2
    axios请求配置
    this.$axios.get('/goods.json',{
    				timeout: 3000
    			}).then()
    
    • 1
    • 2
    • 3
    • 以上配置优先级:请求配置 > 实例配置 > 全局配置

    拦截器

    • 在请求或响应被处理前拦截他们
    请求拦截器
    this.$axios.interceptors.request.use(config=>{
    	// 发生请求前的处理
    
    	return config
    },err=>{
    	// 请求错误处理
    
    	return Promise.reject(err);
    })
    
    //或者用axios实例创建拦截器
    let instance = $axios.create();
    instance.interceptors.request.use(config=>{
        return config
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    响应拦截器
    this.$axios.interceptors.response.use(res=>{
    	//请求成功对响应数据做处理
    
    	return res //该返回对象会传到请求方法的响应对象中
    },err=>{
    	// 响应错误处理
    
    	return Promise.reject(err);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    取消拦截
    let instance = this.$axios.interceptors.request.use(config=>{
    				config.headers = {
    					token: ''
    				}
    				return config
    			})
    			
    //取消拦截
    this.$axios.interceptors.request.eject(instance);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    错误处理

    this.$axios.get('/url').then(res={
    
    }).catch(err=>{
    	//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
    	console.log(err);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    取消请求

    let source = this.$axios.CancelToken.source();
    
    this.$axios.get('/goods.json',{
    	cancelToken: source
    }).then(res=>{
    	console.log(res)
    }).catch(err=>{
    	//取消请求后会执行该方法
    	console.log(err)
    })
    
    //取消请求,参数可选,该参数信息会发送到请求的catch中
    source.cancel('取消后的信息');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
  • 相关阅读:
    LeetCode 138. 复制带随机指针的链表
    LeetCode952三部曲之一:解题思路和初级解法(137ms,超39%)
    【定时功能】消息的定时发送-基于RocketMQ
    dataframe应用str.contains+将多列连接成一列
    [每周一更]-(第23期):Docker 逻辑图及常用命令汇总
    架构师技能9-深入mybatis:Creating a new SqlSession到查询语句耗时特别长
    HTML5网页设计成品:汽车介绍特斯拉 (dreamweaver作业静态HTML网页设计模板)
    shell脚本处理日志转化为JsonArray
    【2024最新华为OD-C/D卷试题汇总】[支持在线评测] 最小配对和(100分) - 三语言AC题解(Python/Java/Cpp)
    软件设计模式系列之二十——备忘录模式
  • 原文地址:https://blog.csdn.net/weixin_44321600/article/details/127713160