微信小程序请求数据,在页面展示,可以在onLoad生命周期中进行请求。
1.新建目录http,新建文件http.js

2.在js文件中暴露需要使用的变量
var baseUrl = 'http://101.89.144.168'; export const httpUrl = { "getContentList": baseUrl + "/api/portals/content/getContentsList", "contentType": "application/x-www-form-urlencoded" //header }
3.设置是否校验请求链接。不设置这个,可能会请求失败。

4.在生命周期onLoad中使用wx.request({})请求数据
import {httpUrl} from '../../http/http.js'
onLoad: function (options) {
console.log(this.data.test);
//引入js
wx.request({
url: httpUrl.getContentList,
data: { "type": "news_normal", "offset": 0, "limit": -1, },
method:"post",
//header也可以写成配置那样的形式
header: {
"Content-Type": httpUrl.contentType
},
//回调函数中使用箭头函数,改变this的指向。
success:res=>{
console.log(res);
console.log(this.data.test);
}
})
},