第一步:后端简单建个springboot项目,提供一个 helloworld接口;
版本选用 2.2.6.release
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
package com.java1234.controller;
import org.springframework.web.bind.annotation.getmapping; import org.springframework.web.bind.annotation.restcontroller;
/** * @author java1234_小锋 * @site HdhCmsTestjava1234测试数据 * @company 南通小锋网络科技有限公司 * @create 2021-07-04 17:43 */ @restcontroller public class helloworldcontroller {
@getmapping ( "/helloworld" ) public string helloworld(integer id){ return "helloworld " +id; } } |
application.yml
1 2 3 4 5 6 |
server: port: 80 servlet: context-path: / tomcat: uri-encoding: utf- 8 |
浏览器访问:http://localhost/helloworld?id=1
页面显示:
helloworld 1
第二步:新建一个helloworld 微信小程序,请求后端
helloworld.js
通过微信小程序api wx.request调用后端接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
// pages/helloworld.js page({
/** * 页面的初始数据 */ data: { result: "请求后台中..." },
/** * 生命周期函数--监听页面加载 */ onload: function (options) { var that= this ; this .getdata(that); },
getdata(that){ wx.request({ url: 'http://localhost/helloworld' , method: "get" , data:{ id: 100 }, header: { 'content-type' : 'application/json' // 默认值 }, success(res){
console.log(res.data); console.log(that) that.setdata({ result:res.data }) } }) },
/** * 生命周期函数--监听页面初次渲染完成 */ onready: function () {
},
/** * 生命周期函数--监听页面显示 */ onshow: function () {
},
/** * 生命周期函数--监听页面隐藏 */ onhide: function () {
},
/** * 生命周期函数--监听页面卸载 */ onunload: function () {
},
/** * 页面相关事件处理函数--监听用户下拉动作 */ onpulldownrefresh: function () {
},
/** * 页面上拉触底事件的处理函数 */ onreachbottom: function () {
},
/** * 用户点击右上角分享 */ onshareappmessage: function () {
} }) |
helloworld.wxml
1 2 |
<!--pages/helloworld.wxml--> <text>返回值:{{result}}</text> |
运行报错了:
vm8 asdebug.js:1 cannot send network request to localhost.(env: windows,mp,1.05.2105170; lib: 2.18.0)
这里我们需要设置下:
详情->本地设置->勾选 [不校验合法域名、web-view (业务域名)、tls版本以及hitps证书]
勾选后,重新编译,运行ok;
扩展下,如果是域名调用,比如 http://localhost 改成 http://HdhCmsTestjava1234测试数据
报错:
如若已在管理后台更新域名配置,请刷新项目配置后重新编译项目,操作路径:[详情-域名信息]
vm8 asdebug.js:1 http://HdhCmsTestjava1234测试数据 不在以下 request 合法域名列表中,请参考文档:https://developers.weixin.qq测试数据/miniprogram/dev/framework/ability/network.html(env: windows,mp,1.05.2105170; lib: 2.18.0)
我们打开 https://developers.weixin.qq测试数据/miniprogram/dev/framework/ability/network.html
微信小程序对于域名调用会有一些限制,还需要配置,比如仅支持https,•域名不能使用 ip 地址(小程序的局域网 ip 除外)或 localhost;
服务器域名请在 「小程序后台-开发-开发设置-服务器域名」 中进行配置:
到此这篇关于小程序与后端java接口交互实现helloworld入门 的文章就介绍到这了,更多相关小程序与后端java接口交互内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/caoli201314/article/details/118499346
查看更多关于小程序与后端Java接口交互实现HelloWorld入门的详细内容...