当前位置:网站首页>微信小程序请求封装
微信小程序请求封装
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);
}
}
边栏推荐
猜你喜欢
Redis cache and existing problems--cache penetration, cache avalanche, cache breakdown and solutions
egg框架中解决跨域的三种方案
php向mysql写入数据失败
ps怎么把图片变清晰,自学ps软件photoshop2022,简单快速用ps让照片更清晰更有质感
MongoDB 语法大全
How to make a puzzle in PS, self-study PS software photoshop2022, PS make a puzzle effect
爬虫从入门到入牢
学习笔记14--机器学习在局部路径规划中的应用
Ethernet Principle
Chapter3、色调映射
随机推荐
spark集群部署(第三弹)
tear apart loneliness
让硬盘更快,让系统更稳定
Qt编写自定义控件:文字聚光灯效果之一
控制器-----controller
【每日一题】1403. 非递增顺序的最小子序列
DataFrame在指定位置插入行和列
Spark cluster deployment (third bullet)
Antdesign a-select 下拉框超出长度换行显示
JS语法使用
ps怎么替换颜色,自学ps软件photoshop2022,ps一张图片的一种颜色全部替换成另外一种颜色
8.4 Summary of the mock competition
D2--FPGA SPI接口通信2022-08-03
Support touch screen slider carousel plugin
Thinking after writing a code with a very high CPU usage
The color of life divine
复现一次循环和两次循环
Chapter 12 Bayesian Networks
[Repost] Marry a man must marry a man whose salary is at least 3571.4 yuan higher than yours
TensorFlow安装步骤