微信小程序:封装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);
          // 处理错误
      }
相关推荐
Goona_14 小时前
PyQt+Excel学生信息管理系统,增删改查全开源
python·小程序·自动化·excel·交互·pyqt
郑州光合科技余经理14 小时前
O2O上门预约小程序:全栈解决方案
java·大数据·开发语言·人工智能·小程序·uni-app·php
weixin_1772972206915 小时前
旧物回收新风尚,绿色生活新篇章——小程序引领环保新潮流
小程序·生活
CHU72903515 小时前
智慧回收新体验:同城废品回收小程序的便捷功能探索
java·前端·人工智能·小程序·php
2501_9160088915 小时前
在不越狱前提下导出 iOS 应用文件的过程,访问应用沙盒目录,获取真实数据
android·macos·ios·小程序·uni-app·cocoa·iphone
2501_9151063215 小时前
Android和IOS 移动应用App图标生成与使用 Assets.car生成
android·ios·小程序·https·uni-app·iphone·webview
计算机毕设指导615 小时前
基于微信小程序的奶茶店点餐系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
2501_9159184115 小时前
Mac 抓包软件有哪些?Charles、mitmproxy、Wireshark和Sniffmaster哪个更合适
android·ios·小程序·https·uni-app·iphone·webview
2501_9151063215 小时前
iOS 抓包绕过 SSL 证书认证, HTTPS 暴力抓包、数据流分析
android·ios·小程序·https·uni-app·iphone·ssl
2501_915921431 天前
iOS App 电耗管理 通过系统电池记录、Xcode Instruments 与克魔(KeyMob)组合使用
android·ios·小程序·https·uni-app·iphone·webview