参考博客
微信小程序开发之网络请求(GET请求)
微信小程序开发之网络请求(POST请求)
微信小程序 不在以下合法域名列表中
目录
- 介绍
- get请求
- post请求
介绍
一个微信小程序,同时只能有5个网络请求连接。
get请求
Api:wx.request(OBJECT)
请求参数说明
示例代码
wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json' // 默认值
},
success: function(res) {
console.log(res.data)
}
})
success返回参数:
请求中断
返回一个 requestTask 对象,通过 requestTask,可中断请求任务。要求最低版本1.4
示例代码
const requestTask = wx.request({
url: 'test.php', //仅为示例,并非真实的接口地址
data: {
x: '' ,
y: ''
},
header: {
'content-type': 'application/json'
},
success: function(res) {
console.log(res.data)
}
})
requestTask.abort() // 取消请求任务
post请求
与get请求差不多,需要修改的是增加一个method :”POST”方法
Tip:
- ‘Content-Type’: ‘application/json’用在get请求中没问题. POST请求就不好使了.需要改成: “Content-Type”: “application/x-www-form-urlencoded”
示例代码:
//logs.js
const util = require('../../utils/util.js')
var app = getApp()
Page({
data: {
toastHidden: true,
city_name: '',
},
onLoad: function () {
that = this;
wx.request({
url: "https://liaolongjun.duapp.com/ace/https.do",
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST",
data: { cur: 1 },
complete: function (json) {
if (json == null || json.data == null) {
console.error('网络请求失败');
return;
}
wx.showModal({
title: "提示",
content: JSON.stringify(json.data),
success: function (res) {
if (res.confirm) {
console.log("用户点击确定")
}
}
});
}
})
},
onToastChanged: function () {
that.setData({ toastHidden: true });
}
})
var that;
//var Util = require('../../utils/util.js');
使用http请求会出现域名不合法的情况,小程序只支持https的请求