文章目录
搭建服务端
npm install -save-dev express
// server.js
const express = require("express");
const server = express();
server.use("/test",function(req,res){
const obj = {
foo:"hello",
bar:"world"
}
res.end(JSON.stringify(obj));
})
server.use("/",function(req,res){
res.end("<h1>hello world</h1>");
})
server.listen(3000,function(){
console.log("listening on *:3000");
})
node server.js
启动服务器,浏览器便可访问网址 http://localhost:3000/
。
小程序
<!-- index.wxml -->
<view>
<button bind:tap="handleClick">click me</button>
</view>
// index.js
Page({
handleClick:function(){
wx.request({
url:"http://localhost:3000/test",
success:function(res){
const {
data} = res;
console.log(data);
}
})
}
})
点击click me,出现如下错误警告:
解决方法是,设置>项目设置>勾选“不校验合法域名、web-view(业务域名)、TLS版本以及HTTPS证书”。
点击click me,控制台打印出响应数据。
小程序与服务端通信
get请求
小程序向服务端发送数据
小程序向服务端发送数据,有两种方式。
- 第一种:数据以查询字符串的形式放在url中
// index.js
Page</