小程序怎么与后端Java接口交互实现HelloWorld

来自:互联网
时间:2023-05-29
阅读:

第一步:后端简单建个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

返回顶部
顶部