参考博客:
(1)wx-request封装:https://www.jianshu.com/p/ad1e5b581e18
(2)setData()方法的使用和注意事项:https://blog.csdn.net/qq_38595560/article/details/81565925
第一步:配置接口域名
在app.js下配置host域名
第二步:在utils下配置request.js
// wx.request封装
const app = getApp()
const request = (url, options) => {
return new Promise((resolve, reject) => {
wx.request({
url: `${app.globalData.host}${url}`,//获取域名接口地址
method: options.method, //配置method方法
data: options.method === 'GET' ? options.data : JSON.stringify(options.data),
//如果是GET,GET自动让数据成为query String,其他方法需要让options.data转化为字符串
header: {
'Content-Type': 'application/json; charset=UTF-8',
'token':token
},
//header中可以监听到token值的变化
success(request) {
//监听成功后的操作
if (request.data.code === 10000) {
//此处10000是项目中数据获取成功后返回的值,成功后将request.data传入resolve方法中
resolve(request.data)
} else {
//如果没有获取成功返回值,把request.data传入到reject中
reject(request.data)
}
},
fail(error) {
//返回失败也同样传入reject()方法
reject(error.data)
}
})
})
}
//封装get方法
const get = (url, options = {}) => {
return request(url, {
method: 'GET',
data: options
})
}
//封装post方法
const post = (url, options) => {
return request(url, {
method: 'POST',
data: options
})
}
//封装put方法
const put = (url, options) => {
return request(url, {
method: 'PUT',
data: options
})
}
//封装remove方法
// 不能声明DELETE(关键字)
const remove = (url, options) => {
return request(url, {
method: 'DELETE',
data: options
})
}
//抛出wx.request的post,get,put,remove方法
module.exports = {
get,
post,
put,
remove
}
第三步:在page中加入一个api文件夹,在下面在加入一个api.js来封装所有的接口
const getMainPage = 'api/mainPage/getMainPage' // 获取首页资源
//抛出getMainPage这个常量
module.exports = {
getMainPage
}
第四步:在pages中子组件的js中引用api.js和request.js
import { getMainPage} from '../api/api.js'
import api from '../../utils/request.js'
第五步:在onload方法中调用接口和方法
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
//调用接口
api.post(getMainPage).then(res => {
//成功时回调函数
console.log(res)
}).catch(err => {
//失败时回调函数
console.log(err)
})
},
备注:
(1)问题1:数据获取成功后,数据为什么在页面内加载不出来
必须使用setData()来触发数据的更新
原因:
可以参考官网地址: https://developers.weixin.qq.com/miniprogram/dev/reference/api/Page.html
Page.prototype.setData(Object data, Function callback)板块
(2)问题2:https的域名后台报错不合法
在本地开发阶段:
在小程序的编辑器中=>点击详情=>勾选不校验合法域名、web-view(业务域名)、TLS 版本以及 HTTPS 证书