学习微信小程序发起一个HTTP请求
0x01客户端配置
1 创建小程序项目
然后编辑index.wxml页面,创建按钮以及对应绑定的函数
<view class="container">
<!-- This is our View -->
<view> Http 响应: {{response}} </view>
<button bindtap="httpRequest"> HTTP请求测试 </button>
</view>
然后编辑index.js页面
//index.js
//获取应用实例
const app = getApp()
var helloData = {
response: ''
}
// Register a Page.
Page({
// data: helloData,
httpRequest: function (e) { //对应:<button bindtap="httpRequest"> http </button>的button点击
var that=this
wx.request({
url: 'http://127.0.0.1:5000/test', // 本地flask接口
method: "POST",
data: {
},
header: {
'content-type': 'application/json' // 默认值
},
success: function (res) {
console.log(res.data)
that.setData({
response: res.data //把接收到的服务器数据显示到{{response}}中
})
}
})
}
})
2 关闭本地域名校验和证书校验(真实环境中,只能请求在控制台中填写的域名,这里只能本地IDE请求类似127.0.0.1这种域名或者ip)
0x02 服务端配置(任意语言都可以,这里为了方便展示用的python-flask)
本地flask为Python3安装的
在默认页面修改接口如下:
from flask import Flask
app = Flask (__name__)
@app.route ('/test',methods=['POST'])
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run ()
运行flask
0x03 测试
点击发起请求
服务端: