微信小程式后端Java介面開發
微信小程式使用wx.request(OBJECT)來呼叫后端介面,
首先 我們來一個簡單案例 —— helloworld實作
1、搭建一個springboot專案并引入依賴

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、撰寫controller層
@RestController
public class HelloWorldController {
@GetMapping("/helloWorld")
public String helloWorld(Integer id){
return "helloworld"+id;
}
}
server:
port: 80
servlet:
context-path: /
tomcat:
uri-encoding: utf-8
運行成功

3、創建微信小程式專案

helloworld.js
/**
* 頁面的初始資料
*/
data: {
result:'請求后臺中.....'
},
/**
* 生命周期函式--監聽頁面加載
*/
onl oad: function (options) {
var that=this;
this.getData(that);
},
getData(that){
wx.request({
url: 'http://localhost:8080/helloWorld',
method:'GET',
data:{
id:666
},
header:{
'content-type':'application/json' //默認值
},
success(res){
console.log(res.data);
console.log(that);
that.setData({
result:res.data
})
}
})
},
helloworld.wxml
<text>后端回傳的資料:{{result}}</text>
注意:!!!!
這里記得設定 如下圖
否則會報錯:
VM9 asdebug.js:1 http://localhost 不在以下 request
合法域名串列中,請參考檔案:https://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html(env:
Windows,mp,1.05.2110110; lib: 2.19.4)

訪問后端成功 如下圖

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/350912.html
標籤:java
