有一串前端js登陆代码:
sendRequest:function(){wx.request({url: `http://localhost:8080/lf/login/2021/2021`,method:'POST',success:(res) => {console.log("测试通过")}})}
和后端代码:
public Result<Students> logginById(@PathVariable String stundentNo,@PathVariable String password){log.info("员工登录:{},{}",stundentNo,password);Students students = userService.LostLogin(stundentNo,password);log.info("继续");return Result.success(students);}
存在问题:
不管前端传递的账号密码是否正确,都会成功调用success回调函数,从而导致无法判断账号密码是否匹配成功。
解决办法:
要避免无论账号密码是否正确都调用success回调函数,可以在后端代码中对账号密码进行验证,只有在验证通过后才返回成功的结果。 修改后端代码如下:
public Result<Students> logginById(@PathVariable String stundentNo, @PathVariable String password) {log.info("员工登录:{},{}", stundentNo, password);Students students = userService.LostLogin(stundentNo, password);if (students != null) { //因为service报错时students没有值log.info("继续");return Result.success(students);} else {// 验证失败,返回错误信息或者错误码return Result.error("账号密码错误");}
}
前端可以通过判断返回结果中的错误信息或错误码来确定是否登录成功。可以在success回调函数中判断返回结果的状态码或错误信息,如果状态码或错误信息表示登录失败,则进行相应的处理,否则表示登录成功。 修改前端代码如下:
sendRequest: function() {wx.request({url: `http://localhost:8080/lf/login/2021/2021`,method: 'POST',success: (res) => {if (res.data.code === 1) { //controller调用成功返回的result的data里的code为1// 登录成功console.log("登录成功");// 进行其他操作} else {// 登录失败console.log("登录失败:" + res.data.msg); //调用失败返回data的msg信息// 进行相应的处理,例如提示用户登录失败}},fail: (res) => {// 请求失败console.log("请求失败:" + res.errMsg);// 进行相应的处理,例如提示用户请求失败}})
}