使用bcryptjs加密密码时出现Illegal arguments错误求助
解决bcryptjs加密时出现"Illegal arguments: undefined, number"错误
错误原因分析
错误信息Error: Illegal arguments: undefined, number明确指向bcrypt.hash(password, 5)调用时第一个参数为undefined,也就是后端未正确获取到前端传入的password值,可能触发场景:
- 前端请求体未包含
password字段,或字段名拼写不一致(比如写成Password/pwd) - 请求的
Content-Type不是application/json,导致request.json()解析失败 - 前端提交的JSON格式有误,无法被正确解构
解决步骤
1. 排查前端请求合法性
- 确认前端POST请求的
Content-Type设置为application/json - 检查请求体的JSON结构,确保包含小写的
password字段,示例正确请求体:{ "name": "test", "email": "test@example.com", "password": "123456" }
2. 后端添加参数校验与调试
在后端代码中先打印请求体确认数据接收情况,并添加必填字段校验,避免undefined传入加密方法:
export const POST = async (request) => { const body = await request.json(); // 调试:打印请求体,确认是否包含password console.log('Received request body:', body); const { name, email, password } = body; // 校验必填字段,提前返回错误 if (!name || !email || !password) { return new NextResponse('缺少必填字段(name/email/password)', { status: 400 }); } await connect(); const hashedPassword = await bcrypt.hash(password, 5); const newUser = new User({ name, email, password: hashedPassword, }); try { await newUser.save(); return new NextResponse('用户创建成功', { status: 201, }); } catch (err) { return new NextResponse(err.message, { status: 500, }); } };
3. 修复User模型的拼写错误
你的User模型中mongoose校验字段存在拼写错误(require应为required),虽不是当前错误直接原因,但会导致后续用户保存时的校验异常,建议修正:
const userSchema = new mongoose.Schema( { name: { type: String, required: true, // 修正require为required }, userName: { type: String, }, email: { type: String, unique: true, required: true, // 修正require为required }, password: { type: String, required: true, // 修正require为required }, registrationDate: { type: Date, default: Date.now, }, avatar: { type: String, }, admin: { type: Boolean, default: false, required: true, // 修正require为required }, // ... 其他字段 }, { timestamps: true }, );
内容的提问来源于stack exchange,提问作者Khuong Viet Tai
相关产品推荐
相关产品推荐

