axios
axios与后台进行数据交互, Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
Axios 是一个基于 promise 的 HTTP 库,简单的讲就是可以发送get、post等请求,可以用在浏览器和 node.js 中。React等框架的出现,促使了Axios轻量级库的出现,因为Vue等,不需要操作Dom,所以不需要引入Jquery.js了。
-
promise
异步编程的一种解决方案
-
所谓Promise,简单说就是一个容器,里面保存着某个未来才会结束的事件(通常是一个异步操作)的结果
-
Promise提供统一的API,各种异步操作都可以用同样的方法进行处理
-
Promise对象代表一个异步操作,有三种状态:Pending(进行中)、Resolved(已完成,又称Fulfilled)和Rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态 (英语意思就是“承诺”,表示其他手段无法改变)
-
与事件(Event)完全不同,事件的特点是,如果你错过了它,再去监听,是得不到结果的。 有了Promise对象,就可以将异步操作以同步操作的流程表达出来,避免了层层嵌套的回调函数
-
axios特性
-
从浏览器创建 XMLHttpRequests
-
从 node.js 创建 http 请求
-
支持 Promise API
-
拦截请求和响应
-
转换请求和响应数据
-
取消请求
-
超时处理
-
查询参数序列化支持嵌套项处理
-
自动将请求体序列化为:
-
JSON (application/json)
-
Multipart / FormData (multipart/form-data)
-
URL encoded form (application/x-www-form-urlencoded)
-
将 HTML Form 转换成 JSON 进行请求
-
自动转换JSON数据
-
获取浏览器和 node.js 的请求进度,并提供额外的信息(速度、剩余时间)
-
为 node.js 设置带宽限制
-
兼容符合规范的 FormData 和 Blob(包括 node.js)
-
客户端支持防御XSRF
-
请求方法
-
get:获取数据,请求指定的信息,返回实体对象
-
post:向指定资源提交数据(例如表单提交或文件上传)
-
put:更新数据,从客户端向服务器传送的数据取代指定的文档的内容
-
patch:更新数据,是对put方法的补充,用来对已知资源进行局部更新
-
delete:请求服务器删除指定的数据
-
head:获取报文首部
安装使用
安装axios
npm install axios -s初始化axios,在utils文件夹下创建request.ts文件
//引入axios
import axios from 'axios';
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({
// axios中请求配置有baseURL选项,表示请求URL公共部分
baseURL: import.meta.env.VITE_APP_BASE_API,
// baseURL: "http://localhost:8085/mumudemo/",
timeout: 5000 // 请求超时时间
});
// 添加请求拦截器
/*需要拦截请求的原因
* 1.config中包含了某些不符合服务器要求的信息
* 2.发送网络请求的时候需要向用户展示一些加载中的图标
* 3.网站需要登录才能请求资源,也就是需要token才能请求资源
*/
// 添加响应拦截器
// 响应拦截器
//导出
export default service;
创建.env.development文件,按需修改内容
# 页面标题 VITE_APP_TITLE = mumudemo # 开发环境配置 VITE_APP_ENV = 'development' # mumudemo/开发环境 VITE_APP_BASE_API = '/mumudemo'
使用时只需引入request.ts即可
封装axios及使用案例
前端代码
在创建的api文件夹的test文件夹中创建axiosRequest.ts
import request from '@/utils/axios/request'
// get请求 不带params(Restful风格)封装方法 注意,拼接风格url使用反引号
export function restfulGet(id: number | string) {
return request({
url: `/test/restfulGet/${id}`,
method: 'get'
})
}
// 无参get请求
export function noParams() {
return request({
url: '/test/noParams',
method: 'get'
})
}
// 带params(传统风格)
export function haveParams(id: number | string) {
return request({
url: '/test/haveParams',
method: 'get',
params: { id: id }
})
}
// 传统风格带params的get请求 后端用@RequestParam注解绑定参数值
export function getDel(id: number | string) {
return request({
url: '/test/del',
method: 'get',
params: { id: id }
})
}
// post请求
export function postA(data) {
return request({
url: '/test/add',
method: 'post',
data: data
})
}
// put请求
export function putA(data) {
return request({
url: '/test/update',
method: 'put',
data: data
})
}
// delete请求
export function delA(ids) {
return request({
url: '/test/' + ids,
method: 'delete'
})
}
创建index.vue页面
<template>
<div>
<el-button type="primary" @click="restfulGetF">restfulGet</el-button>
</div>
<div>
<el-button type="primary" @click="noParamsF">noParams</el-button>
</div>
<div>
<el-button type="primary" @click="haveParamsF">haveParams</el-button>
</div>
<div>
<el-button type="primary" @click="getDelF">getDel</el-button>
</div>
<div>
<el-button type="primary" @click="postAF">postA</el-button>
</div>
<div>
<el-button type="primary" @click="putAF">putA</el-button>
</div>
<div>
<el-button type="primary" @click="delAF">delA</el-button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import {
restfulGet,
delA,
getDel,
putA,
postA,
noParams,
haveParams,
} from '../../../api/test/axiosRequest';
// 定义响应式数据
const form1 = ref({ a: 'a' });
const id = ref(1);
const ids = ref(2);
// restful风格get
const restfulGetF = () => {
console.log(id.value);
restfulGet(id.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in fetchString:', error);
});
};
// 无参get请求
const noParamsF = () => {
console.log(id.value);
noParams()
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in fetchB:', error);
});
};
// 有参get请求
const haveParamsF = () => {
console.log(id.value);
haveParams(id.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in fetchB:', error);
});
};
// 更新A的函数
const putAF = () => {
putA(form1.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in updateA:', error);
});
};
// 创建A的函数
const postAF = () => {
postA(form1.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in createA:', error);
});
};
// 删除A的函数
const delAF = () => {
console.log(ids.value); //注意使用.value传参
delA(ids.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in deleteA:', error);
});
};
// get删除函数
const getDelF = () => {
console.log(id.value);
getDel(id.value)
.then(response => {
console.log(response);
})
.catch(error => {
console.error('Error in fetchDeleteE:', error);
});
};
</script>
<style scoped>
</style>
后端代码
TestAxios 类
@Data
public class TestAxios {
private String a = null;
}
testController 类
@Api(tags="test")
@RestController
@RequestMapping("/test")
@Slf4j
public class testController {
// restful风格请求
@GetMapping(value = "/restfulGet/{id}")
public Result<String> restfulGet(@PathVariable("id") Integer id) {
System.out.println(111);
return Result.OK("字符串");
}
// 无参get请求
@GetMapping(value = "/noParams")
public void noParams() {
System.out.println(222);
}
// 传统风格带params的get请求
@GetMapping(value = "/haveParams")
public void haveParams(Long id) {
System.out.println(333);
}
// 传统风格带params的get请求 后端用@RequestParam注解绑定参数值
@GetMapping("/del")
public void remove(@RequestParam("id") Integer id) {
System.out.println(444);
}
// post请求
@PostMapping("/add")
public void add(@RequestBody TestAxios testAxios) {
System.out.println(555);
}
// put请求
@PutMapping("/update")
public void edit(@RequestBody TestAxios testAxios) {
System.out.println(666);
}
// delete请求
@DeleteMapping("/{ids}")
@Transactional
public void remove(@PathVariable Long[] ids) {
System.out.println(777);
}
}