前端请求接口数据的参数和返回结果都很类似,并且会频繁请求,效率很重要的嘛,所以封装原生的网络请求就很必要啦;再者,在回调函数中继续编写代码,如果还有回调那就会很臃肿,容易形成回调地
封装wx.request
http.js
const pubUrl = "http://localhost:3000/api"//这是我要请求的数据接口的公共部分
const http = (options) =>{
return new Promise((resolve,reject) => {
wx.request({
url: pubUrl+options.url,
method:options.method || 'get',
data:options.data || {},
header: options.header || {
'content-type':'application/x-www-form-urlencoded'
},
success:resolve,
fail:reject
})
})
}
export default http
api.js (这里主要是对要请求的接口进行了封装,接口会有很多,放在同一个文件中方便管理)
import http from 'http.js' //引入上面封装好的请求方法
// 获取商品的一级分类,不需要参数
const _getTopCate = () => {
return http({
url:'/getcate'
})
}
//获取商品详情,需要传入参数
const _getDetail = (id) => {
return http({
url:'/getgoodsinfo',
data:{
id
}
})
}
// 将方法导出,实现复用
export default{
_getTopCate,
_getDetail
}
具体需要请求数据的页面的js文件,如:index.js
import Api from '../../utils/api.js' //首先要引入封装好的上述api文件,路径根据自己文件的位置
Page({
data:{
},
// 因为请求数据的方法用promise封装,所以需要配合async 和 await 来获取到promise中的数据
async _getCate(){ //在需要请求接口获取数据的方法中调用api中的方法
let result = await Api._getTopCate();
console.log(result);
},
async _getDetail(){
let result = await Api._getDetail(1);
console.log(result)
}
})
顺便也看看index.wxml文件吧
<view bindtap="_getCate">获取一级分类</view> //点击会触发上述js中的_getCate()事件,然后调用封装的接口获取到数据
<view bindtap="_getDetail">请求数据商品详情</view>
大功告成!这样就封装好了