微信小程序:封装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);
          // 处理错误
      }
相关推荐
贝格前端工场15 分钟前
小程序订阅消息设计:用户触达与隐私保护的平衡法则
大数据·小程序
weixin_lynhgworld17 分钟前
盲盒一番赏小程序:用科技重新定义“未知的快乐”
科技·小程序
Bruce_Json1 小时前
微信小程序ts+sassjlin-ui
微信小程序·小程序·sass
来碗盐焗星球2 小时前
记一次微信小程序AI开发的血泪史
前端·微信小程序
说私域4 小时前
淘宝直播与开源链动2+1模式AI智能名片S2B2C商城小程序的融合发展研究
人工智能·小程序·开源
说私域7 小时前
互联网生态下赢家群体的崛起与“开源AI智能名片链动2+1模式S2B2C商城小程序“的赋能效应
人工智能·小程序·开源
The_era_achievs_hero14 小时前
微信小程序71~80
微信小程序·小程序
dssxyz15 小时前
uniapp打包微信小程序主包过大问题_uniapp 微信小程序时主包太大和vendor.js过大
javascript·微信小程序·uni-app
!win !16 小时前
被老板怼后,我为uni-app项目引入环境标志
前端·小程序·uni-app
澄江静如练_20 小时前
微信小程序发体验版
微信小程序·小程序