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);// 处理错误}