当前位置:网站首页>uniapp Request请求封装的方法
uniapp Request请求封装的方法
2022-07-16 18:09:00 【生命不止、战斗不息】
封装方法一
1.新建request.js

const baseUrl = "http://localhost:6645"
const request = (url = '', date = {}, type = 'POST', header = {
'content-type': 'application/x-www-form-urlencoded'
}) => {
return new Promise((resolve, reject) => {
uni.request({
method: type,
url: baseUrl + url,
data: date,
header: header,
dataType: 'json',
}).then((response) => {
setTimeout(function() {
uni.hideLoading();
}, 200);
let [error, res] = response;
resolve(res.data);
}).catch(error => {
let [err, res] = error;
reject(err)
})
});
}
export default request2.在main.js中全局注册
import request from "api/request.js"
Vue.prototype.$request = request
3.在页面中调用
this.$request('/recruit/getAll', {
// 传参参数名:参数值,如果没有,就不需要传
}).then(res => {
// 打印调用成功回调
console.log(res)
})4.效果如下

优缺点
优点:方便快捷,效率高
缺点:请求方法没有完全封装,还是散落在页面各处,后期维护不方便
封装方法二
1.新建请求文件

const baseUrl = "http://localhost:6645"
// 获取所有招聘信息
export function getAllRecruit() {
return uni.request({
url: baseUrl + '/recruit/getAll', //仅为示例,并非真实接口地址。
method: 'POST',
header: {
'content-type': 'application/x-www-form-urlencoded' //自定义请求头信息
}
});
}2.在页面中导入
import {getAllRecruit} from "../../api/recruit_info.js"3,在created周期函数中调用
created() {
// 获取所有招聘信息
getAllRecruit().then(res =>{
console.log(res)
})
}4.效果图、

优缺点
优点:请求方法封装在单独的文件夹中,页面中只需要调用,不需要其他的业务代码,便于维护
缺点:需要导入,导出,代码比方法一多一些
边栏推荐
- Daily question · sword finger offer | 041 Average value of sliding window (same as 346) · queue
- [book club issue 13] +ffmpeg command
- 整蛊小程序(宝宝,我是天下第一大傻X)代码
- Trickery applet (baby, I'm the biggest fool in the world x) code
- 20. Network principles - Basic Concepts
- Metrics学习笔记
- 开口就要20k的软件测试工程师需要掌握哪些技能?有这些技能我敢要更高~
- BRITS: Bidirectional Recurrent Imputation for Time Series(时间序列的双向递归填补)论文详解
- Code that programmers can't guess
- 一场羽绒服直播GMV狂涨430%,反季热销的秘诀原来是这个?
猜你喜欢
随机推荐
ccf真题(怒拿100昏)
长安链tls基础研究
Trapped in the marketing siege, how long can Hua Xizi bear the title of "light of domestic goods"?
基于 Servlet 项目——博客系统
千万级别数据mysql distinct group by
Splunk configuring multi cluster index
21. How does the program execute after entering the URL in the browser?
Tiktok protocol interface, protocol analysis add_ x_ bogus add_ signature
Theoretical knowledge of static routing
A down jacket live broadcast Gmv soared by 430%. Is this the secret of off-season hot sales?
程序员都猜不到的代码
R语言使用vtreat包的designTreatmentsC函数构建数据处理计划(treatment plan)、使用vtreat包进行数据准备
Installation and deployment series (I) -- docker compose installation of redis cluster cluster
你猜不到的代码
[in-depth learning] experience of renting online equipment platform and the pits (non advertising)
R语言ggplot2可视化:ggplot2可视化密度图(density plot)并使用geom_vline函数添加均值竖线、添加均值数值标签(Mean Line or Vertical Line )
解决数据库连接池HikariCP问题
最近有点忙。
[Xuelang download tutorial] 05 Xuelang download's official packet capture Download
高级程序员面试常用问题,你知道回答吗? 带答案








