当前位置: 首页 > article >正文

微信小程序:封装request请求

1、定义一个request.js类

// 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请求

//封装的请求方法
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请求

requestWithToken('Homepage/sel_YearInfo', 'GET')
      .then(response => {
          console.log('Protected resource:', response);
          // 处理响应数据
      })
      .catch(error => {
          console.error('Error:', error);
          // 处理错误
      }


http://www.kler.cn/a/469356.html

相关文章:

  • LeetCode 面试题01.04回文排列
  • 用户界面的UML建模10
  • 《燕云十六声》游戏文件损坏怎么解决?
  • ELK+filebeat+kafka
  • 网络编程基础:连接Java的秘密网络
  • 手搓一个ChatUI需要分几步
  • 提示词工程教程:提示词安全
  • 在K8S中,如何查看kubelet组件的日志?
  • 【模型】Qwen2-VL 服务端UI
  • 【服务器常见网络攻击】
  • 基于Arduino的FPV头部追踪相机系统
  • PHP进阶-php文件读取与连接数据库基础部分
  • redis相关概念介绍
  • phpStorm环境配置与应用
  • C# 设计模式(行为型模式):模板方法模式
  • PHP7和PHP8的最佳实践
  • k8s中,Containerd运行时与Dockerd运行时区别
  • githu报错:ssh: connect to host github.com port 22: Connection timed out
  • 我用Ai学Android Jetpack Compose之Composable函数
  • jenkins入门4 --window执行execute shell