微信小程序:封装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);
          // 处理错误
      }
相关推荐
小羊Yveesss6 小时前
2026年知识付费小程序多少钱一个?
小程序
一只皮卡皮卡丘6 小时前
微信小程序tab页苹果显示安卓不显示的问题
微信小程序·小程序
六月的可乐6 小时前
【干货】小程序虚拟瀑布流探索小结
前端·react.js·小程序
前端 贾公子1 天前
小程序蓝牙打印探索与实践(上)
小程序
拙慕JULY1 天前
小程序返回 base64 文件报错
开发语言·javascript·小程序
dh131222505251 天前
按月季度销售业绩核算小程序
小程序·销售小程序·绩效小程序·业绩统计小程序·业绩核算小程序
拙慕JULY1 天前
微信小程序自定义标题背景色
微信小程序·小程序
前端 贾公子1 天前
小程序蓝牙打印探索与实践(下)
小程序·apache
00后程序员张1 天前
Jenkins 自动上传 IPA 到 App Store 把发布步骤融入 CI/CD
android·ios·小程序·https·uni-app·iphone·webview
万岳科技系统开发1 天前
骑手配送系统如何支持外卖与跑腿一体化运营
大数据·前端·小程序