You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何处理NextJS后端API返回的64位有符号整数?

解决NextJS前后端64位整数解析问题

问题原因

JSON本身不支持64位整数类型,当后端用res.json()返回BigInt类型的userId时,Node.js会自动将其序列化为{high, low, unsigned}的结构(这是V8引擎对BigInt的内部拆分表示),前端拿到的就是这个拆分后的对象,自然没法直接用parseInt或BigInt解析。

最优解决方案:后端转字符串返回

直接在后端把64位整数转成字符串输出,这是最稳妥的方式,彻底避免前后端类型适配问题:

// 后端路由修改代码
res.status(200).json({ id: userId.toString(), attributes: userAttributes });

前端拿到数据后,根据需求转换类型:

  • 如果userId在Number安全范围(小于2^53-1),用Number(response.data.id)转换
  • 超出安全范围的话,用BigInt(response.data.id)转成BigInt类型使用

后端无法修改时:前端手动重构BigInt

如果没法调整后端代码,可以通过high和low字段手动计算出原始的64位整数:

function getUserIdFromParts(high, low, unsigned) {
  const highBig = BigInt(high) << 32n;
  const lowBig = BigInt(low);
  let result = highBig | lowBig;
  // 处理有符号负数的情况
  if (!unsigned && (high & 0x80000000)) {
    result -= 1n << 64n;
  }
  return result;
}

// 前端使用示例
const userId = getUserIdFromParts(
  response.data.id.high,
  response.data.id.low,
  response.data.id.unsigned
);

内容的提问来源于stack exchange,提问作者dokgu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 10:52:43