Appearance
❤axios认识使用
1. 认识
官网地址
axios官网地址:www.axios-js.com/
axios中文文档:www.axios-js.com/zh-cn/docs/
在线的CND地址
JS
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
简介
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
2. axios特点
● 支持promise:使用Promise管理异步,告别传统callback方式
● 支持node端和浏览器端:同样的API,node和浏览器全支持,平台切换无压力
● 丰富的配置项:支持拦截器等高级配置
● 从浏览器中创建XMLHttpRequests
3. 安装使用
(1)安装依赖
JS
NPM使用的时候安装
npm install axios
yarn使用安装
yarn add axios
(2)在需要的页面导入
JS
import axios from 'axios'
(3)使用
JS
axios.get('地址').then(res=>{
console.log(res,'axios请求返回')
});
4. 单页面使用
完整案例
先来看看一个完整的get请求案例,通过案例来学习axios的使用
JS
import axios from 'axios'
// 获取用户
function getUserList() {
let api = "http://localhost:8888/api/user";
// console.log(queryParams.value,'queryParams.value'); //查询条件
const params = {
name: queryParams.value.name,
age: queryParams.value.age,
pageNum: queryParams.value.pageNum,
pageSize: queryParams.value.pageSize,
};
axios({
method: 'get',
url: api,
headers: {
'Authorization': 'Bearer ' + localStorage.getItem("login"),
'Content-Type': 'application/json;charset=utf-8',
'Custom-Header': 'custom-value'
},
params: params,
})
.then(res => {
console.log(res.data);
if (res.status == 200) {
// console.log(res, 'res');
tableData.value = res.data.data;
totalvalue.value = res.data.total;
}
})
.catch(error => {
console.error(error);
});
}
获取用户get请求
JS
// 获取用户信息
function getUserinfo() {
let api = "http://localhost:8888/api/getInfo";
axios({
method: 'get',
url: api,
headers: {
'Authorization': xxx这里是得到的token信息 => 比如 localStorage.getItem("login")
'Content-Type': 'application/json;charset=utf-8',
'Custom-Header': 'custom-value'
},
})
.then(res => {
console.log(res.data);
if (res.status == 200) {
console.log(res, 'res-获取用户信息');
}
})
.catch(error => {
console.error(error);
});
}
接下来我们项目之中的增删改查接口为例看看如何使用axios
获取列表
JS
import axios from 'axios';
const apiUrl = "http://localhost:8888/api/user";
// 获取所有用户数据
function handleQuery() {
axios.get(apiUrl)
.then(res => {
if (res.status === 200) {
console.log('所有用户数据:', res.data);
// 这里可以进行数据的渲染或更新界面
}
})
.catch(err => {
console.error('获取用户数据失败:', err);
});
}
新增
JS
import axios from 'axios';
const apiUrl = "http://localhost:8888/api/user";
// 增加一个新用户
function handleAdd(row) {
let data = {
name: row.name,
email: row.email,
// 添加其他用户信息
};
axios.post(apiUrl, data)
.then(res => {
if (res.status === 201) { // 201 是成功创建的 HTTP 状态码
console.log('用户添加成功');
handleQuery(); // 刷新数据
}
})
.catch(err => {
console.error('添加用户失败:', err);
});
}
获取详情
JS
// 获取单个用户详情
function handleGetDetails(id) {
let api = `${apiUrl}/${id}`;
axios.get(api)
.then(res => {
if (res.status === 200) {
console.log('用户详情:', res.data);
// 这里可以进行用户详情的渲染或更新界面
}
})
.catch(err => {
console.error('获取用户详情失败:', err);
});
}
修改提交
JS
import axios from 'axios';
const apiUrl = "http://localhost:8888/api/user";
// 修改用户信息
function handleUpdate(row) {
let api = `${apiUrl}/${row.id}`;
let data = {
name: row.name,
email: row.email,
// 更新其他需要修改的用户信息
};
axios.put(api, data)
.then(res => {
if (res.status === 200) {
console.log('用户修改成功');
handleQuery(); // 刷新数据
}
})
.catch(err => {
console.error('修改用户失败:', err);
});
}
删除请求
JS
// 删除用户信息
function handleDelete(row) {
let id = row.id;
let api = "http://localhost:8888/api/user/" + id;
let data = { id: row.id };
console.log(row.id, 'row.id');
axios.delete(api, data).then(res => {
if (res.status == 200) {
// console.log(res, '删除成功');
handleQuery(); // 刷新数据
}
})
}
提交文件
JS
// 提交文件
当点击上传按钮时,执行上传文件的函数
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const progressBar = document.getElementById('progressBar');
const status = document.getElementById('status');
// 获取用户选择的文件
const file = fileInput.files[0];
if (file) {
// 创建一个FormData对象,用于将文件数据发送到服务器
const formData = new FormData();
formData.append('file', file); // 将文件添加到FormData中
console.log(formData.file, 'formData');
// 创建一个XMLHttpRequest对象,用于发送HTTP请求
const xhr = new XMLHttpRequest();
// 配置请求,指定上传的URL和请求方法
xhr.open('POST', 'http://localhost:8888/api/upload', true);
// 监听上传进度事件,更新进度条和状态文本
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
progressBar.value = percent;
status.innerText = `上传中: ${percent.toFixed(2)}%`;
}
};
// 监听上传完成事件
xhr.onload = function() {
if (xhr.status === 200) {
status.innerText = '上传完成';
} else {
status.innerText = '上传失败';
}
};
// 监听上传错误事件
xhr.onerror = function() {
status.innerText = '上传错误';
};
// 发送FormData对象到服务器
xhr.send(formData);
} else {
status.innerText = '请选择文件';
}
}
5. 封装和详细使用
(1)执行get请求
JS
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
(2)执行post请求:
JS
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
(3)执行多个并发请求:
JS
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
js
上述案例来自axios中文文档:www.axios-js.com/zh-cn/docs/
6. 封装axios
实际项目里为了更方便使用axios获取后台数据会进行封装。
vue项目里封装一般放在utils文件夹里,src下新建utils文件夹=>新建index.js文件
JS
import axios from 'axios';
let baseURL;
if(process.env.NODE_ENV=='development'){
baseURL = 'http://xxxx:3000/api'
}else{
baseURL = '/xxx'
}
// baseURL es6 方法
const $http = axios.create({
baseURL,
})
// create 是axios自带的方法
export const get = (url,params)=>{
params = params || {};
return new Promise((resolve,reject)=>{
// axiso 自带 get 和 post 方法
$http.get(url,{
params,
}).then(res=>{
if(res.data.status===0){
resolve(res.data);
}else{
alert(res.data.msg)
}
}).catch(error=>{
alert('网络异常');
})
})
}
export const post = (url,params)=>{
params = params || {};
return new Promise((resolve,reject)=>{
$http.post(url,params).then(res=>{
if(res.data.status===0){
resolve(res.data);
}else{
alert(res.data.msg);
}
}).catch(error=>{
alert('网络异常');
})
})
}
☞ main.js文件中做如下配置:
JS
import { get, post } from "./utils/index";
Vue.prototype.$http = {
get,
post
};
(1)使用构造函数的原型prototype(vue属于构造函数);
(2)声明一个全局变量并且把封装好的get和post方法放在里面,使用封装后的函数:
js
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/film/getList";
// 要访问第二页的话在网址后面加 ?type=2&pageNum=页数
const res = await this.$http.get(url);
this.filmList = res.films;
},
注意:因为是promise封装的函数方法,所以使用的时候要加上async 函数(){ await 数据} 不然会报错,因为没有完成异步转同步。