微信小程序封装API接口
1. 首先在微信小程序管理后台中注册域名
2. 新建文件夹http,api是封装的接口函数,env是设置公共访问的url,http是二次封装wx.request();
3. env.js
//设置公共访问的url,即环境变量
module.exports = {
// 开发环境
dev: {
baseUrl: 'http://localhost:3000'
},
// 测试环境
test: {
baseUrl: 'www.test.com'
},
// 线上环境
prod: {
baseUrl: 'https://api.it120.cc'
}
}
4. http.js
// 引入env中的url
const {
baseUrl
} = require('./env.js').prod
// 专属域名
const subDomain = '域名'
module.exports = {
/**二次封装wx.request()
* url:请求的接口地址
* method:请求方式
* data传参
* */
request: (url, method = 'GET', data = {}, isSubDomain) => {
// console.log(baseUrl)
let _url = `${baseUrl}/${isSubDomain?subDomain:''}${url}`
return new Promise((resolve, reject) => {
wx.showLoading({
title:"正在加载"
})
wx.request({
url: _url,
data: data,
method: method,
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: (res) => {
// console.log(res)
let {code}=res.data
if(code==0){
wx.hideLoading()
resolve(res.data)
}else{
wx.showToast({
title: '数据请求失败',
})
}
}
})
})
}
}
5. api.js
// 引入request请求
const {
request
} = require('./http')
// 基于业务封装的接口
module.exports = {
/**
* 拿封装商品列表举例
*/
// url,method,data,isSubDomain
getGoodsList: () => {
// console.log('获取商品列表方法')
return request('/shop/goods/list','get',{},true); //第一个参数为地址,第二个参数为请求方式,第三个参数为传递的参数,第四个参数为是否需要token
},
//.........可以根据自己的数据继续封装
}
6. 页面上使用时
首先先引入封装好的接口函数
const { getGoodsList} = require('../../http/api')
然后在onLoad生命周期函数中调用
onLoad:function(option){
//商品列表
getGoodsList().then(res => {
// console.log(res) //res即是请求到的数据
this.setData({
goodslist:res.data
})
})
},