首頁  >  文章  >  Java  >  小程式怎麼與後端Java介面互動實作HelloWorld

小程式怎麼與後端Java介面互動實作HelloWorld

WBOY
WBOY轉載
2023-05-27 17:07:061632瀏覽

第一步:後端簡單建置一個SpringBoot項目,提供一個helloWorld介面;

版本選用2.2.6.RELEASE

package com.java1234.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author java1234_小锋
 * @site www.java1234.com
 * @company 南通小锋网络科技有限公司
 * @create 2021-07-04 17:43
 */
@RestController
public class HelloWorldController {

    @GetMapping("/helloWorld")
    public String helloWorld(Integer id){
        return "helloWorld "+id;
    }
}

application.yml

server:
  port: 80
  servlet:
    context-path: /
  tomcat:
    uri-encoding: utf-8

瀏覽器訪問:http://localhost/helloWorld?id=1

頁面顯示:

helloWorld 1

第二步:新一個helloWorld 微信小程序,請求後端

helloWorld.js

透過微信小程式API wx.request呼叫後端介面

// 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

<!--pages/helloWorld.wxml-->
<text>返回值:{{result}}</text>

執行報錯了:

小程式怎麼與後端Java介面互動實作HelloWorld

VM8 asdebug.js:1 Cannot send network request to localhost.(env: Windows,mp,1.05.2105170; lib: 2.18.0)

這裡我們需要設定下:

詳情->本地設定->勾選「不校驗合法網域、web-view (業務網域)、TLS版本以及HITPS憑證」

小程式怎麼與後端Java介面互動實作HelloWorld

#勾選後,重新編譯,運行OK;

小程式怎麼與後端Java介面互動實作HelloWorld

#擴展下,如果是網域調用,例如http://localhost 改成http://www.java1234.com

報錯:

小程式怎麼與後端Java介面互動實作HelloWorld

#如若已在管理後台更新網域配置,請刷新專案配置後重新編譯項目,操作路徑:「詳情-網域資訊」
VM8 asdebug.js:1 http://www.java1234.com 不在以下request 合法網域清單中

微信小程式對於網域呼叫會有一些限制,還需要配置,例如僅支援https,•網域不能使用IP 位址(小程式的區域網路IP 除外)或localhost;

伺服器網域請在「小程式後台-開發-開發設定-伺服器域名” 中進行設定:

小程式怎麼與後端Java介面互動實作HelloWorld

以上是小程式怎麼與後端Java介面互動實作HelloWorld的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除