小程序数据请求

为了安全考虑,小程序官方对数据接口做了限制

  • 只能请求 HTTPS 类型的接口
  • 必须将接口的域名添加至信任列表中

配置 request 合法域名

  1. 第一步,先登录小程序管理平台
  2. 选择开发分类下的 开发管理 -> 开发设置

applets-dev-settins

  1. 滚动至服务器域名设置

applets-domain-settin

  1. 配置 request 合法域名

发送 GET 请求

1
2
3
4
5
6
7
8
9
10
wx.request({
url: '',
method: 'get',
data: {
id: 321215411
},
success: (res) => {
console.log(res)
}
})

发送 POST 请求

1
2
3
4
5
6
7
8
9
10
wx.request({
url: '',
method: 'post',
data: {
username: 'ruins'
},
success: (res) => {
console.log(res)
}
})

页面初始化时发送请求

onLoad 为微信小程序页面加载时所触发的生命周期钩子函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
page({
getInfo() {
wx.request({
url: '',
method: 'get',
data: {
id: 321215411
},
success: (res) => {
console.log(res)
}
})
},

onLoad: function (options) {
this.getInfo()
}
})

在微信小程序中是不存在跨域问题和 AJAX 请求的,而是发起网络数据请求