[小程序]Http网络请求
warning:
这篇文章距离上次修改已过196天,其中的内容可能已经有所变动。
在微信小程序中,可以使用wx.request
进行HTTP网络请求。以下是一个示例代码,展示了如何在微信小程序中发起一个GET请求:
wx.request({
url: 'https://example.com/api/data', // 你的API地址
method: 'GET', // 请求方法
dataType: 'json', // 返回的数据格式
success: function(res) {
// 请求成功的处理
console.log(res.data);
},
fail: function(error) {
// 请求失败的处理
console.error(error);
}
});
对于POST请求,你可以这样做:
wx.request({
url: 'https://example.com/api/data', // 你的API地址
method: 'POST', // 请求方法
data: {
key: 'value' // 你要发送的数据
},
header: {
'content-type': 'application/x-www-form-urlencoded' // 设置请求的 header
},
success: function(res) {
// 请求成功的处理
console.log(res.data);
},
fail: function(error) {
// 请求失败的处理
console.error(error);
}
});
请确保你的小程序有权限发起网络请求,并且API地址是合法的,否则请求可能失败。
评论已关闭