文章目录
- 前言
- 一、方法参考站
- 二、使用步骤
- 1.首先需要创建api文件夹,在文件夹里创建api.js文件
- 2.修改app.js
- 3.页面里使用
- 总结
前言
最近在写小程序项目,为了节约代码量,以及为了防止后期多处修改地址容易出问题或者遗漏,所以对数据请求进行了封装操作,具体操作如下。
提示:以下是本篇文章正文内容,下面案例可供参考
一、方法参考站
二、使用步骤
1.首先需要创建api文件夹,在文件夹里创建api.js文件
api.js 代码如下(示例):
根据自己的数据需求更改调整即可
const app = getApp()const request = (url, options) => {let header = {}if (options.method == 'POST') {header = {'content-type': 'application/x-www-form-urlencoded',}} else {header = {'content-type': 'application/json',}}return new Promise((resolve, reject) => {wx.request({// {app.globalData.host}为接口请求中的公共部分写在app.js中url: `${app.globalData.host}${url}`,method: options.method,data: options.method === 'GET' ? options.data : JSON.stringify(options.data) && options.method === 'POST' ? options.data : options.data,header: header,success(request) {if (request.data.code === '20000') {resolve(request.data)} else {reject(request.data)}},fail(error) {reject(error.data)}})})
}const get = (url, options = {}) => {return request(url, { method: 'GET', data: options })
}
const post = (url, options) => {return request(url, { method: 'POST', data: options })
}
const put = (url, options) => {return request(url, { method: 'PUT', data: options })
}
// 不能声明DELETE(关键字)
const remove = (url, options) => {return request(url, { method: 'DELETE', data: options })
}module.exports = {get,post,put,remove
}
2.修改app.js
app.js 代码如下(示例):
//app.jsApp({onLaunch: function () {},globalData: {host: "这里是你要访问的后端地址",},})
3.页面里使用
在需要使用数据请求的页面.js文件里 代码如下(示例):
import api from '../../api/api' //根据你自己的路径引入文件
Page({/*** 页面的初始数据*/data: {ewmImg:'',//二维码图片},/*** 生命周期函数--监听页面加载*/onLoad(options) {this.getewmImg()},// 获取二维码图片getewmImg('你要传输的数据'){var that = thisapi.post('/weixin/qrcode-img', '你要传输的数据').then(res => {that.setData({ewmImg:res.data.qrcodeimg})}).catch(err => { })},/*** 生命周期函数--监听页面初次渲染完成*/onReady() {},/*** 生命周期函数--监听页面显示*/onShow() {},/*** 生命周期函数--监听页面隐藏*/onHide() {},/*** 生命周期函数--监听页面卸载*/onUnload() {},/*** 页面相关事件处理函数--监听用户下拉动作*/onPullDownRefresh() {},/*** 页面上拉触底事件的处理函数*/onReachBottom() {},/*** 用户点击右上角分享*/onShareAppMessage() {}
})