微信小程序连接本机(localhost)后台测试

  1. 本机接口 本地后台搭建一个springBoot项目,测试接口如下:
@RestController
@RequestMapping("/api/v0")
public class TestController {

    @PostMapping("/add")
    public String add(@RequestBody Object object){
        System.out.println(object.toString());
        return "OK";
    }

    @GetMapping("/get")
    public String get(@RequestParam String id){
        return id;
    }
}
  1. 小程序本机接口引入 小程序中创建与pages同级目录public,public下创建api.js文件 api.js
const API = {
  add: "http://localhost:8066/api/v0/add",
  get: "http://localhost:8066/api/v0/get"
};
module.exports = API;

在需要调用接口的小程序页面js文件中引入接口(我使用的页面是demo04) 接口调用方法 同样是在需要引入接口的页面js文件中

  1. 本机调用 以上基本需要的已经配置完成,但是在小程序界面触发调用接口时出现错误: 小程序调用接口的域名应该时https的,此时本机测试并不需要去申请https域名, 解决方法:详情-本地设置中,勾选“不校验合法域名…” 再次触发调用接口方法,可以看到小程序成功调用本机接口。
经验分享 程序员 微信小程序 职场和发展