当前位置:网站首页>微信小程序请求封装
微信小程序请求封装
2022-08-05 08:18:00 【wam923259736】
在utils文件夹下新建request.js
// 同时发送异步代码的次数
let ajaxTimes=0;
export const request=(params)=>{
// 判断 url中是否带有 /my/ 请求的是私有的路径 带上header token
let header={
...params.header};
if(params.url.includes("/my/")){
// 拼接header 带上token
header["Authorization"]=wx.getStorageSync("token");
}
ajaxTimes++;
// 显示加载中 效果
wx.showLoading({
title: "加载中",
mask: true
});
// 定义公共的url
const baseUrl ="https://itheima.net/api/public/v1";
return new Promise((resolve,reject)=>{
wx.request({
...params,
header:header,
url:baseUrl+params.url,
success:(result)=>{
resolve(result.data.message);
},
fail:(err)=>{
reject(err);
},
complete:()=>{
ajaxTimes--;
if(ajaxTimes===0){
// 关闭正在等待的图标
wx.hideLoading();
}
}
});
})
}
在页面中引入并使用
// 获取轮播图数据
getSwiperList(){
// 默认为method: 'get'
request({
url: "/home/swiperdata" })
.then(result => {
this.setData({
swiperList: result
})
})
},
method为post的情况
// 获取用户信息
async handleGetUserInfo(e) {
try {
// 1 获取用户信息
const {
encryptedData, rawData, iv, signature } = e.detail;
// 2 获取小程序登录成功后的code
const {
code } = await login();
const loginParams={
encryptedData, rawData, iv, signature ,code};
// 3 发送请求 获取用户的token
const {
token}=await request({
url:"/users/wxlogin",data:loginParams,method:"post"});
// 4 把token存入缓存中 同时跳转回上一个页面
wx.setStorageSync("token", token);
wx.navigateBack({
delta: 1
});
} catch (error) {
console.log(error);
}
}
边栏推荐
- Luogu P1966: [NOIP2013 提高组] 火柴排队 [树状数组+逆序对]
- Stored procedure writing experience and optimization measures
- 苹果官网商店新上架Mophie系列Powerstation Pro、GaN充电头等产品
- TensorFlow installation steps
- The magic weapon for small entrepreneurs!
- CROS和JSONP配置
- Beautifully painted MM set
- pnpm 是凭什么对 npm 和 yarn 降维打击的
- unity 头发的渲染
- 在原有数据库基础上执行sql文件有则跳过没有则添加如何实现?
猜你喜欢

Chapter 12 贝叶斯网络

SVG big fish eat small fish animation js special effects

MySQL 数据库 报错 The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid)

Ethernet Principle

MySQL database error The server quit without updating PID file (/var/lib/mysql/localhost.localdomain.pid)

ps怎么把图片变清晰,自学ps软件photoshop2022,简单快速用ps让照片更清晰更有质感

MongoDB 语法大全

EA谈单机游戏:仍是产品组合中极其重要的部分

Adb 授权过程分析

网络安全研究发现,P2E项目遭遇黑客攻击只是时间问题
随机推荐
JVM运行流程,运行时数据区,类加载,垃圾回收,JMM解析
长期招聘嵌入式开发-深圳宝安
v-if/v-else determines whether to display according to the calculation
Adb authorization process analysis
青苹果论坛重新开放
Thinking after writing a code with a very high CPU usage
Fiddler tool explanation
uniapp时间组件封装年-月-日-时-分-秒
国际原子能机构总干事称乌克兰扎波罗热核电站安全形势堪忧
真正爱你的女人是这样的
【结构体内功修炼】结构体内存对齐(一)
剑指Offer面试题解总结1-10
k-nearest neighbor fault monitoring based on multi-block information extraction and Mahalanobis distance
[NOIP2010 提高组] 机器翻译
nn.unfold和nn.fold
How to replace colors in ps, self-study ps software photoshop2022, replace one color of a picture in ps with another color
【无标题】长期招聘硬件工程师-深圳宝安
php fails to write data to mysql
执子之手,与子偕老。你同意么?
SVG星球大战样式Toggle切换开关按钮