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

Node.js电商后端API加密密码时触发RangeError: Invalid array length错误

问题:Node.js电商API密码加密时触发RangeError: Invalid array length

错误日志

...\ECommerceApi\node_modules\crypto-js\core.js:335
words.length = Math.ceil(sigBytes / 4);
                                 ^

RangeError: Invalid array length
    at WordArray.init.clamp (D:\STUDY\React.JS\reactproject\ECommerceApi\node_modules\crypto-js\core.js:335:27)

相关代码

const router = require("express").Router();
const User = require("../models/User")
const CryptoJS = require("crypto-js")

//REGISTER
router.post("/register",async (req,res)=>{
    
    const newUser = new User({
        username:req.body.username,
        email:req.body.email,
        password:CryptoJS.AES.encrypt(req.body.password,process.env.PASS_SEC).toString()
 

    });
    try{

        const savedUser = await newUser.save();
        res.status(201).json(savedUser)
        console.log(savedUser)
    }catch(err){
        res.status(500).json(err)
        console.log(err);
    }
});
    

module.exports = router;

错误原因及解决方法

  • 核心原因:CryptoJS.AES.encrypt的两个参数(明文密码、加密密钥)中存在空值或未定义的情况,导致加密过程无法生成有效的WordArray,进而触发数组长度异常。

  • 解决步骤:

    1. 检查请求参数:在POSTMAN中确认请求Body里正确传递了password字段,无论是form-data还是raw JSON格式,都要保证该字段存在且有有效值。
    2. 验证环境变量:
      • 确认项目根目录的.env文件中已正确设置PASS_SEC变量,且值不为空字符串;
      • 确保项目入口文件(如server.js)中已加载环境变量,添加代码require('dotenv').config()(需先安装dotenv包:npm install dotenv)。
    3. 增加参数校验:在加密逻辑前添加判断,提前拦截空值请求,避免无效加密操作:
      router.post("/register",async (req,res)=>{
          // 新增校验
          if (!req.body.password || !process.env.PASS_SEC) {
              return res.status(400).json({ message: "密码或加密密钥不能为空" });
          }
      
          const newUser = new User({
              username:req.body.username,
              email:req.body.email,
              password:CryptoJS.AES.encrypt(req.body.password,process.env.PASS_SEC).toString()
          });
          // ... 后续代码不变
      });
      
    4. 排查版本问题:若上述步骤无效,尝试重装CryptoJS到稳定版本:
      npm uninstall crypto-js
      npm install crypto-js@4.1.1
      

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:15:43