后端返回的数据:
@GetMapping("/checkUserNameWithPassword")
public ResponseEntity<Long> checkUserNameWithPassword(UserList userList) {
System.out.println("CHECK DATA:\tname:" + userList.getUsername() + "\tpassword:" + userList.getPassword());
if (userListMapper.findUserNameWithPassword(userList)) {
String userName = userList.getUsername();
Long id = Long.parseLong(userListMapper.getUserId(userName));
System.out.println("id find by password:" + id);
return ResponseEntity.status(HttpStatus.OK).body(id);
} else {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(403L);
}
}
后端的打印:
我们可以看到,id的最后三位为216
但是前端打印:
原因是因为在JavaScript中,最大安全整数是2的53次方-1(即9007199254740991),如果您的MongoDB中的_id值超过这个范围,JavaScript会出现长整数精度丢失的问题。
解决方案:
1.
为了解决这个问题,可以使用MongoDB的ObjectId类型来存储_id,它是一个12字节的值,可以确保唯一性和正确性,并且可以在JavaScript中轻松地处理。您可以使用以下代码将字符串转换为
const { ObjectId } = require('mongodb');
const idString = 'your_id_string';
const objectId = new ObjectId(idString);
然后,使用objectId变量来处理_id,并且不会出现长整数精度丢失的问题。
2.
可以使用第三方JavaScript库来处理大整数。例如,可以使用BigInteger.js库,该库支持高精度整数运算,并且可以处理超过JavaScript最大安全整数范围的值。可以使用以下代码将字符串转换为BigInteger:需要使用的时候可以转会为String类型即可
const value = BigInt(res.data);
console.log(value)
wx.setStorageSync('id', value.toString())