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

Node.js中使用crypto模块时TypeError错误的解决方法

解决TypeError [ERR_INVALID_ARG_TYPE]密码加密错误

这个错误的核心原因是调用getHash(user.password, salt)时,user.password的值为undefined,不满足crypto.pbkdf2Sync对第一个参数的类型要求(必须是字符串或Buffer类实例)。以下是具体排查和解决步骤:

  • 校验传入的user对象完整性
    在addNewUser函数开头添加参数校验,提前拦截无效输入,避免后续报错:

    const addNewUser = function(user, done) {
        // 检查user是否存在,且password为非空字符串
        if (!user || typeof user.password !== 'string' || user.password.trim() === '') {
            return done(new Error('密码不能为空且必须是有效字符串'), null);
        }
        const salt = crypto.randomBytes(64); 
        const hash = getHash(user.password, salt); 
        // 后续SQL操作代码...
    }
    
  • 给哈希函数添加参数校验
    为getHash函数增加参数合法性检查,提前抛出明确错误,方便调试:

    const getHash = function (password, salt) {
        if (typeof password !== 'string') {
            throw new Error('password参数必须是字符串类型');
        }
        if (!Buffer.isBuffer(salt)) {
            throw new Error('salt参数必须是Buffer类型');
        }
        return crypto
         .pbkdf2Sync(password, salt, 100000, 256, 'sha256')
         .toString('hex')
    }
    
  • 排查请求数据解析问题(Web接口场景)
    如果是基于Express等Web框架开发,确保已正确配置请求体解析中间件,否则前端传来的password字段无法被正确解析到user对象中:

    const express = require('express');
    const app = express();
    
    // 解析JSON格式的请求体
    app.use(express.json());
    // 解析表单格式的请求体(如果需要)
    app.use(express.urlencoded({ extended: true }));
    
    app.post('/register', (req, res) => {
        // req.body即为前端传入的用户数据,确认包含password字段
        addNewUser(req.body, (err, userId) => {
            if (err) {
                return res.status(400).json({ error: err.message });
            }
            res.status(201).json({ userId });
        });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 23:55:30