9-AJAX-下-axios

一 axios是什么

上古浏览器页面在向服务器请求数据时,因为返回的是整个页面的数据,页面都会强制刷新一下,这对于用户来讲并不是很友好。并且我们只是需要修改页面的部分数据,但是从服务器端发送的却是整个页面的数据,十分消耗网络资源。而我们只是需要修改页面的部分数据,也希望不刷新页面,因此异步网络请求就应运而生。

Ajax(Asynchronous JavaScript and XML):异步网络请求。Ajax能够让页面无刷新的请求数据。

实现ajax的方式有多种,如jQuery封装的ajax,原生的XMLHttpRequest,以及axios。但各种方式都有利弊

  1. 原生的XMLHttpRequest的配置和调用方式都很繁琐,实现异步请求十分麻烦
  2. jQuery的ajax相对于原生的ajax是非常好用的,但是没有必要因为要用ajax异步网络请求而引用jQuery框架

Axios,可以理解为ajax i/o system,这不是一种新技术,本质上还是对原生XMLHttpRequest的封装,可用于浏览器和nodejs的HTTP客户端,只不过它是基于Promise的,符合最新的ES规范。

二 Axios请求方式

1、axios可以请求的方法:

get:获取数据,请求指定的信息,返回实体对象

post:向指定资源提交数据(例如表单提交或文件上传)

put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容

patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新

delete:请求服务器删除指定的数据

2、get请求

示例代码
方法一

js 复制代码
 //请求格式类似于 http://localhost:8080/goods.json?id=1
this.$axios.get('/goods.json',{
    			params: {
                    id:1
                }
			}).then(res=>{
					console.log(res.data);
				},err=>{
					console.log(err);
			})

方法二

js 复制代码
this.$axios({
		method: 'get',
		url: '/goods.json',
    	params: {
            id:1
        }
	}).then(res=>{
		console.log(res.data);
	},err=>{
		console.log(err);
	})

3、post请求

post请求一般分为两种类型

  1. form-data 表单提交,图片上传、文件上传时用该类型比较多

  2. application/json 一般是用于 ajax 异步请求

示例代码

方法一

js 复制代码
this.$axios.post('/url',{
				id:1
			}).then(res=>{
				console.log(res.data);
			},err=>{
				console.log(err);
			})

方法二

js 复制代码
$axios({
	method: 'post',
	url: '/url',
	data: {
		id:1
	}
}).then(res=>{
	console.log(res.data);
},err=>{
	console.log(err);
})

form-data请求

js 复制代码
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);
})

4、put和patch请求

示例代码
put请求

js 复制代码
this.$axios.put('/url',{
				id:1
			}).then(res=>{
				console.log(res.data);
			})

patch请求

js 复制代码
this.$axios.patch('/url',{
				id:1
			}).then(res=>{
				console.log(res.data);
			})

5、delete请求

示例代码
参数以明文形式提交

js 复制代码
this.$axios.delete('/url',{
				params: {
					id:1
				}
			}).then(res=>{
				console.log(res.data);
			})

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

js 复制代码
//方法二
axios({
    method: 'delete',
    url: '/url',
    params: { id:1 }, //以明文方式提交参数
    data: { id:1 } //以封装对象方式提交参数
}).then(res=>{
	console.log(res.data);
})

6、并发请求

并发请求:同时进行多个请求,并统一处理返回值
示例代码

js 复制代码
 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);
	})
)

三 Axios实例

1、创建axios实例

示例代码

js 复制代码
let instance = this.$axios.create({
				baseURL: 'http://localhost:9090',
				timeout: 2000
			})
			
instance.get('/goods.json').then(res=>{
	console.log(res.data);
})

可以同时创建多个axios实例。

axios实例常用配置:

  • baseURL 请求的域名,基本地址,类型:String
  • timeout 请求超时时长,单位ms,类型:Number
  • url 请求路径,类型:String
  • method 请求方法,类型:String
  • headers 设置请求头,类型:Object
  • params 请求参数,将参数拼接在URL上,类型:Object
  • data 请求参数,将参数放到请求体中,类型:Object

2、axios全局配置

示例代码

js 复制代码
//配置全局的超时时长
this.$axios.defaults.timeout = 2000;
//配置全局的基本URL
this.$axios.defaults.baseURL = 'http://localhost:8080';

3、axios实例配置

示例代码

js 复制代码
let instance = this.$axios.create();
instance.defaults.timeout = 3000;

4、axios请求配置

示例代码

js 复制代码
this.$axios.get('/goods.json',{
				timeout: 3000
			}).then()

以上配置的优先级为:请求配置 > 实例配置 > 全局配置

四、拦截器

拦截器:在请求或响应被处理前拦截它们

1、请求拦截器

示例代码

js 复制代码
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
})

2、响应拦截器

示例代码

js 复制代码
this.$axios.interceptors.response.use(res=>{
				//请求成功对响应数据做处理

				return res //该返回对象会传到请求方法的响应对象中
			},err=>{
				// 响应错误处理

				return Promise.reject(err);
			})

3、取消拦截

示例代码

js 复制代码
let instance = this.$axios.interceptors.request.use(config=>{
				config.headers = {
					token: ''
				}
				return config
			})
			
//取消拦截
this.$axios.interceptors.request.eject(instance);

五、错误处理

示例代码

js 复制代码
this.$axios.get('/url').then(res={

			}).catch(err=>{
				//请求拦截器和响应拦截器抛出错误时,返回的err对象会传给当前函数的err对象
				console.log(err);
			})

七、取消请求

示例代码

js 复制代码
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('取消后的信息');
相关推荐
子春一212 分钟前
Flutter 2025 可访问性(Accessibility)工程体系:从合规达标到包容设计,打造人人可用的数字产品
前端·javascript·flutter
白兰地空瓶18 分钟前
别再只会调 API 了!LangChain.js 才是前端 AI 工程化的真正起点
前端·langchain
jlspcsdn1 小时前
20251222项目练习
前端·javascript·html
行走的陀螺仪2 小时前
Sass 详细指南
前端·css·rust·sass
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
React 怎么区分导入的是组件还是函数,或者是对象
前端·react.js·前端框架
LYFlied2 小时前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
子春一22 小时前
Flutter 2025 国际化与本地化工程体系:从多语言支持到文化适配,打造真正全球化的应用
前端·flutter
QT 小鲜肉2 小时前
【Linux命令大全】001.文件管理之file命令(实操篇)
linux·运维·前端·网络·chrome·笔记
羽沢313 小时前
ECharts 学习
前端·学习·echarts