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

使用bcrypt哈希密码时Postman测试API报错求助

bcrypt哈希密码报错:data must be a string or Buffer and salt must either be a salt string or a number of rounds

这个错误的核心原因是bcrypt.hashSync接收的第一个参数(待哈希的密码)不是有效的字符串/Buffer,或者根本不存在。以下是具体排查和解决步骤:

1. 校验请求体中的密码有效性

在执行哈希操作前,先判断密码是否存在且为字符串类型,避免无效值传入bcrypt:

import bcrypt from "bcrypt"
import { userModel } from "../../database/models/user.model.js"

export const checkEmail = async(req,res,next) => {
    // 新增密码校验逻辑
    if (!req.body.password || typeof req.body.password !== 'string') {
        return res.status(400).json({ message: "请提供有效的密码字符串" });
    }

    let user = await userModel.findOne({ email : req.body.email})
    if (user) return res.json({message:"email already exists."})

    req.body.password = bcrypt.hashSync(req.body.password, 8)
    next()
}

2. 检查Postman请求配置

  • 确保请求方法为POST/PUT,且在请求Body中正确传入password字段:
    • 若用raw JSON格式,需保证JSON结构合法,示例:
      {
        "email": "test@example.com",
        "password": "yourSecurePassword123"
      }
      
    • 若用form-data格式,需确保键名是password,值为字符串类型

3. 确认Express的请求体解析中间件

如果使用Express框架,必须配置对应的中间件解析请求体,否则req.body会是空对象,导致无法获取到密码:

// 在你的Express主入口文件中添加
import express from 'express';
const app = express();

// 解析JSON格式请求体
app.use(express.json());
// 解析form-data格式请求体
app.use(express.urlencoded({ extended: true }));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 08:31:02