前言
最近做计算机专业设计,学习了一下uniapp,不可避免地需要使用请求,首先接触的是uni.request请求,由于个人开发习惯,总喜欢将容易冗余的部分封装起来。所以封装了一个简单的请求。仅供参考。
操作开始
请求封装
首先在项目中创建一个utils文件夹,在这个文件夹创建一个js文件。代码如下:
文件名:request.js
// 全局请求路径,也就是后端的请求基准路径
const BASE_URL = 'http://localhost:8181'
// 同时发送异步代码的次数,防止一次点击中有多次请求,用于处理
let ajaxTimes=0;
// 数据请求封装
// 封装请求方法,并向外暴露该方法
export const myHttp = (options)=>{
// 解构请求头参数
let header = {...options.header};
// 当前请求不是登录时请求,在header中加上后端返回的token
if(options.url != 'login'){
header["client-identity"] = uni.getStorageSync('session_id');
}
ajaxTimes++;
// 显示加载中 效果
uni.showLoading({
title: "加载中",
mask: true,
});
return new Promise((resolve,reject)=>{
console.log("请求地址:"+BASE_URL+options.url+",请求方式:"+options.method)
uni.request({
url:BASE_URL+options.url,
method: options.method || 'GET',
data: options.data || {},
header,
success: (res)=>{
resolve(res)
},
fail: (err)=>{
reject(err)
},
// 完成之后关闭加载效果
complete:()=>{
ajaxTimes--;
if(ajaxTimes===0){
// 关闭正在等待的图标
uni.hideLoading();
}
}
})
})
}
// 封装请求方法,并向外暴露该方法
// 文件上传请求封装
export const upload = (options)=>{
ajaxTimes++;
// 显示加载中 效果
uni.showLoading({
title: "加载中",
mask: true,
});
return new Promise((resolve,reject)=>{
console.log("请求地址:"+BASE_URL+options.url+",请求方式:"+options.method)
uni.uploadFile({
url:BASE_URL+options.url,
filePath: options.data,
name: 'file',
success: (res)=>{
resolve(res)
},
fail: (err)=>{
reject(err)
},
// 完成之后关闭加载效果
complete:()=>{
ajaxTimes--;
if(ajaxTimes===0){
// 关闭正在等待的图标
uni.hideLoading();
}
}
})
})
}
Api封装
当项目中接口过多时,需要修改还需要寻找相应的页面文件,觉得过于麻烦,故而再对相应同一地址的接口进行封装,如此方便修改也减少了代码量。
举例说明
创建一个api文件夹,这里面统一存放api
拿一个用户登录的请求举例,还是一样,创建一个js文件
文件名:accountApi.js
import {myHttp} from '../utils/request.js'
const address='/account'
class accountApi {
//登录
async login(data){
const res= await myHttp({
url:address+'/login',
data:data,
method:'POST'
})
return res.data;
}
//注册
async register(data){
const res=await myHttp({
url:address+'/insert',
data:data,
method:'POST'
})
return res.data;
}
//修改密码
async update(data){
const res=await myHttp({
url:address+'/update',
data:data,
method:'PUT'
})
return res.data;
}
}
//将api暴露出去
export default new accountApi()
页面中使用
//此为数据(登录表单)
data() {
return {
user: {
username: '',
password: '',
}
};
},
//
methods: {
//登录请求
async login(){
const _this=this
const res= await accountApi.login(_this.user)
console.warn(res)
if(res.code!==200){
return uni.showToast({
title:res.msg,
duration: 1500,
icon:'none'
})
}
//res.code===200时才能跳到下面
//赋值给全局变量username
getApp().globalData.username=this.user.username
uni.switchTab({
url: '../home/home'
})
}
}
如此,便完成了一个登录请求啦,本次完结,撒花!
另外还有一个文件上传的,经过实践说明,文件和参数一起上传容易发生问题,还是文件单独上传为妙,上传完毕后把url存下来,再把url和参数一起提交(相当于发起两次请求,文件,表单分开)。
如对大家有用!请动动小手点赞支持一下博主吧!