实现微信小程序与java后端的代码对接,包含get和post两种方式
1、微信小程序代码
1.1、 文件路径,所有与后端对接的js方法都定义在该文件中,要写好方法注释
${path}\mojie_crm_oa_applet\utils\api.js
代码模板,以下分为GET方式和POST方式两种,使用时请严格区分使用,需要替换路径地址,需要和后端的路径地址对应,如:“login”、“crm/mojieSysMiniMenu/getUserMenuInfo”;同时修改方法名称如:loginSystem、queryMiniMenuInfo;最后要写明方法注释。
A)、POST方式
/**
* 吉燕锋 2023-2-14 16:22:11登录接口login
*/
loginSystem_POST方法名(params) {
return this._request
.postRequest(this._baseUrl + "login", params)
.then((res) => res.data);
}
B)、GET方式
/**
* 吉燕锋 2023-2-15 16:22:31 查询用户的菜单权限信息 menuInfo
*/
queryMiniMenuInfo_GET方法名(params) {
return this._request
.getRequest(this._baseUrl + "crm/mojieSysMiniMenu/getUserMenuInfo", params)
.then((res) => res.data);
}
1.2、 文件路径,1.1中定义的方法的使用,在各自的业务模块对应的js文件中,本例中在login.js和index.js中,注意方法的入参格式,方法名要使用自己定义的方法。使用代码如下:
app.api.定义的方法名(入参JSON类型).then(
function (data) {
console.log(data)
if (data.code == 200) {
// TODO 成功之后执行的业务逻辑
res.rows.map((row, index) => {
row.leaveTypeLabel = that.data.dictData.leave_type.filter((item) => item.value == row.leaveType)[0].label
})
} else {
wx.showToast({
title: data.msg,
icon: "none",
duration: 2000,
});
}
},
(e) => {
console.log(e);
wx.showToast({
title: "网络异常",
icon: "none",
duration: 2000,
});
}
);
2、后端代码
A)、POST方式
// 方法1,使用java对象接收参数
@PostMapping("/login")
public AjaxResult login(@RequestBody LoginBody loginBody)
{
// 在impl中写业务逻辑
return success();
}
// 方法2,使用JSONObject对象接收参数
@PostMapping("/login")
public AjaxResult login(@RequestBody JSONObject jsonObject)
{
// 在impl中写业务逻辑
return success();
}
B)、GET方式
// 方法1,适合入参为多参数和参数类型如果为复杂对象非基本类型
@GetMapping(value = "/getUserMenuInfo")
public AjaxResult getUserMenuInfo(@RequestParam(required = false) Map<String, Object> params)
{
return success(mojieSysMiniMenuService.getUserMenuInfo(Long.valueOf(String.valueOf(params.get("userId")))));
}
// 方法2,适合入参为单参数和参数数量较少的场景,且数据为基本类型
@GetMapping(value = "/getUserMenuInfo")
public AjaxResult getUserMenuInfo(Long userId)
{
return success();
}
@GetMapping(value = "/getUserMenuInfo")
public AjaxResult getUserMenuInfo(Long userId, String username, Float num)
{
return success();
}
3、其他引用的js文件
3.1、request.js文件
/**
* 2021年2月19日15:22:42
*
* 1、在构造函数里创建默认请求的http header,可以在header里配制一些内容,在对应请求方法中如果没有设置header参数,
* 就使用此默认header参数;
* 2、以get post delete put等方法对request进行封装,在发起网络请求不需要重复的写wx.request({method:xxx})这些代码,
* 只要调用getRequest、postRequest等方法就可以了;
* 3、在rquest的结果返回处理函数success中,判定服务端返回的状态代码,对于200状态代码的按业务处理成功处理,
* 对于非200的状态码按异常处理。
* 4、预留统一异常处理函数处理接口,可以通过setErrorHandler来设置统一的异常处理,这样对于一些可以统一处理的异常
* 就不用在业务页面里去重复处理了,例如后端返回401的代码,就可以统一转到登录页面让用户登录了;
* 5、此request不限定服务提供者,可以是自己开发的业务服务端,也可以用于第三方服务的调用;
*
*/
class request {
constructor() {
this._header = {};
}
/**
* 设置统一的异常处理
*/
setErrorHandler(handler) {
this._errorHandler = handler;
}
/**
* GET类型的网络请求
*/
getRequest(url, data, header = this._header) {
return this.requestAll(url, data, header, "GET");
}
/**
* DELETE类型的网络请求
*/
deleteRequest(url, data, header = this._header) {
return this.requestAll(url, data, header, "DELETE");
}
/**
* PUT类型的网络请求
*/
putRequest(url, data, header = this._header) {
return this.requestAll(url, data, header, "PUT");
}
/**
* POST类型的网络请求
*/
postRequest(url, data, header = this._header) {
return this.requestAll(url, data, header, "POST");
}
/**
* 网络请求
*/
requestAll(url, data, header, method) {
return new Promise((resolve, reject) => {
wx.request({
url: url,
data: data,
header: header,
method: method,
timeout: 15000,
success: (res) => {
if (res.statusCode === 200) {
//200: 服务端业务处理正常结束
resolve(res);
} else {
//其它错误,提示用户错误信息
if (this._errorHandler != null) {
//如果有统一的异常处理,就先调用统一异常处理函数对异常进行处理
this._errorHandler(res);
}
reject(res);
}
},
fail: (res) => {
if (this._errorHandler != null) {
this._errorHandler(res);
}
reject(res);
},
});
});
}
}
export default request;
3.2、api.js文件,定义接口地址的文件
/**
* 2021年2月19日15:38:22
*
* 1、实现所有业务服务调用;
* 2、实现统一的异常处理,并传给request;
* 3、将服务端返回的结果response转成response.data回传给API调用的地方;
*/
import request from "./request.js";
class api {
constructor() {
// 生产环境
// this._baseUrl = "http://mojiekeji:8580/"; // 不校验https
// this._baseUrl = "https://mojiekeji.cn:8443/"; // 校验https
// 开发环境
this._baseUrl = "http://localhost:8580/"
this._uploadUrl = "common/upload";
this._defaultHeader = { "Content-Type": "application/json" };
this._request = new request();
this._request.setErrorHandler(this.errorHander);
}
/**
* 吉燕锋 2023-2-14 16:22:11 根据code 到后台换取 openid, sessionKey, unionId
*/
getOpenId(params) {
return this._request
.getRequest(this._baseUrl + "common/getOpenId", params)
.then((res) => res.data);
}
/**
* 吉燕锋 2023-2-14 16:22:11登录接口login
*/
loginSystem(params) {
return this._request
.postRequest(this._baseUrl + "login", params)
.then((res) => res.data);
}
/**
* 吉燕锋 2023-2-15 16:22:31 查询用户的菜单权限信息 menuInfo
*/
queryMiniMenuInfo(params) {
return this._request
.getRequest(this._baseUrl + "crm/mojieSysMiniMenu/getUserMenuInfo", params)
.then((res) => res.data);
}
/**
* 统一的异常处理方法
*/
errorHander(res) {
console.error(res);
}
}
export default api;
3.3、app.js全局js文件
// app.js
import api from "./utils/api.js";
App({
onLaunch() {
// 展示本地存储能力
const logs = wx.getStorageSync("logs") || [];
logs.unshift(Date.now());
wx.setStorageSync("logs", logs);
// 获取用户当前设置
wx.getSetting({
success(res) {
console.log(res);
// 返回值
// authSetting:
// scope.address: true
// scope.invoice: true
// scope.invoiceTitle: true
// scope.userInfo: true // 这里主要用这个
// scope.userLocation: true
// __proto__: Object
// errMsg: "getSetting:ok"
if (res.authSetting["scope.record"] && !res.authSetting["scope.userLocation"]) {
wx.authorize({
scope: "scope.userLocation",
success() {
// 用户已经同意小程序使用定位功能,当再次调用wx.getLocation()方法时,不会再次询问。
wx.getLocation();
},
});
}
if (res.authSetting && !res.authSetting["scope.userInfo"]) {
// 执行未登录操作
// 获取code方法
wx.login({
success: (res) => {
// 发送 res.code 到后台换取 openid, sessionKey, unionId
new api().getOpenId({ code: res.code }).then((res) => {
// 这步是token接口的请求
console.log("获取openid返回信息" + JSON.stringify(res));
if (res.code == 200) {
// 获取本地缓存中的TOKEN
const TOKEN = wx.setStorageSync("openid", res.openid);
wx.getUserProfile({
desc: "关联注册用户信息", // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
success: (res) => {
console.log(res);
if (res.errMsg == "getUserProfile:ok") {
// 成功的操作
console.log("成功的操作,成功获取用户信息");
this.setData({
userInfo: res.userInfo,
hasUserInfo: true,
});
} else {
// 失败的操作
console.log("失败的操作" + res);
}
},
});
} else {
console.log("获取openid失败的操作" + res);
}
});
},
});
}
},
});
},
api: new api(),
globalData: {
userInfo: null,
},
});
3.4、新增的js文件中要在顶部写上以下代码
const app = getApp();