失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 微信小程序封装request请求数据

微信小程序封装request请求数据

时间:2023-03-10 03:26:56

相关推荐

微信小程序封装request请求数据

遇到问题不要慌

做项目离不开请求数据

1.为什么要封装api去请求接口数据

做微信小程序的时候请求数据的时候会多次用到wx.request请求,如果每次都去写一遍

wx.request({url: 'example.php', //仅为示例,并非真实的接口地址data: {x: '',y: ''},header: {'content-type': 'application/json' // 默认值},success (res) {console.log(res.data)}})

反复的复制这段代码,会让自己的项目代码比较冗余,接下来就需要封装一个api去有效的管理接口请求

额 就不多说废话了,直接上代码了

首先在util文件下新建一个api.js文件

api封装代码

const GET = 'GET';const POST = 'POST';const PUT = 'PUT';const FORM = 'FORM';const DELETE = 'DELETE';const baseURL = ':8001';function request(method, url, data) {return new Promise(function(resolve, reject) {let header = {'content-type': 'application/json',};wx.request({url: baseURL + url,method: method,data: method === POST ? JSON.stringify(data) : data,header: header,success(res) {console.log(res);//请求成功返回数据resolve(res.data);},fail(err) {//请求失败reject(err)console.log(err);}})})}// 请求不同的接口const API = {getListData: () => request(GET, `/index/index`),SearchGoodsListApi:() => request(GET,`/search/index`) };module.exports = {API}

在自己需要发请求的页面调用这个api就可以使用了

在.js文件里引入api.js下的API

//引入api.js文件 ,通过$api.xxx( )去调用接口获取数据const $api = require('../../utils/api').API; Page({/*** 页面的初始数据*/data: {dataList: [ ]},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {// 调用接口列表页数据请求$api.getListData().then(res => {//请求成功console.log(res.data);}).catch(err => {//请求失败})//搜索商品的数据请求$api.SearchGoodsListApi().then(res => {//请求成功console.log(res.data);}).catch(err => {//请求失败})},})

请求成功,返回的数据

上面我所使用的接口真实有效,没有接口的小伙伴可以使用此接口测试,封装的api是否报错

如果觉得《微信小程序封装request请求数据》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。