微信小程序:封装request请求

1、定义一个request.js类

javascript 复制代码
// utils/request.js
const app = getApp();

function requestWithToken(url, method = 'GET', data = {}) {
    return new Promise((resolve, reject) => {
        // 发送请求
        wx.request({
            url: app.globalData.position + url,
            header: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            method: method,
            data: data,
            success: res => {
                if (res.statusCode === 200) {
                    resolve(res.data);
                } else {
                    // 其他错误处理
                    wx.showToast({
                        title: '请求失败,请稍后重试',
                        icon: 'none'
                    });
                    reject(new Error('Request failed'));
                }
            },
            fail: err => {
                reject(err);
            }
        });
    });
}

// 导出封装的请求函数
module.exports = {
    requestWithToken
};

这里的 url: app.globalData.position + url,,

app.globalData.position:是在全局变量定义的position,例如++http://域名/api/++

后者url:是传递的url地址

2、页面执行请求

POST请求

javascript 复制代码
//封装的请求方法
requestWithToken('Homepage/sel_YearInfo', 'POST', formData)
.then(response => {
    console.log('Form submitted successfully:', response);
    that.setData({
        monthinfo:response.info
    })
})
.catch(error => {
    console.error('Error submitting form:', error);
    // 处理错误
});

GET请求

javascript 复制代码
requestWithToken('Homepage/sel_YearInfo', 'GET')
      .then(response => {
          console.log('Protected resource:', response);
          // 处理响应数据
      })
      .catch(error => {
          console.error('Error:', error);
          // 处理错误
      }
相关推荐
码云之上12 小时前
微信小程序设备指纹实践,删了重装还能认出这台手机吗?
前端·安全·微信小程序
源码手记17 小时前
基于微信小程序的相亲交友智能匹配系统-附源码
微信小程序·小程序·交友
源码手记18 小时前
基于微信小程序的图书馆座位预约系统(程序+文档)
微信小程序·小程序
aimartec21 小时前
企业小程序与APP定制源码买断工程实践:三层解耦架构、状态机防呆与平滑迁移清单
小程序·架构
源码手记1 天前
基于微信小程序的校园失物招领系统-附源码
微信小程序·小程序
源码手记1 天前
基于微信小程序的体育场馆预约系统-源码文档
微信小程序·小程序
源码手记1 天前
基于微信小程序的物业管理系统-附源码
微信小程序·小程序
千寻技术帮2 天前
50055_基于AI的互帮互助小程序(源码+文档+数据库脚本+部署教程)
数据库·人工智能·小程序·毕业设计·springboot·课程设计
千寻技术帮2 天前
微信小程序血压管理系统设计与实现_50054(Spring Boot + Vue + MySQL)
spring boot·小程序·vue·毕业设计·课程设计·血压助手
用户788477316343 天前
小程序提审被拒 7 次复盘:审核备注怎么写、隐私接口怎么声明
微信小程序