微信小程序:封装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);
          // 处理错误
      }
相关推荐
Uyker1 小时前
从零开始制作小程序简单概述
前端·微信小程序·小程序
打小就很皮...7 小时前
HBuilder 发行Android(apk包)全流程指南
前端·javascript·微信小程序
说私域11 小时前
定制开发开源AI智能名片驱动下的海报工厂S2B2C商城小程序运营策略——基于社群口碑传播与子市场细分的实证研究
人工智能·小程序·开源·零售
说私域17 小时前
内容力重塑品牌增长:开源AI大模型驱动下的智能名片与S2B2C商城赋能抖音生态种草范式
人工智能·小程序·开源·零售
前端缘梦19 小时前
微信小程序登录方案实践-从账号体系到用户信息存储
前端·微信小程序
coding随想1 天前
2025年小程序开发全解析:技术储备、行业趋势与实战案例
微信小程序
Nueuis1 天前
微信小程序前端面经
前端·微信小程序·小程序
轩1151 天前
实现仿中国婚博会微信小程序
微信小程序·小程序
知否技术2 天前
2025微信小程序开发实战教程(一)
前端·微信小程序
喝牛奶的小蜜蜂2 天前
个人小程序:不懂后台,如何做数据交互
前端·微信小程序·小程序·云开发