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

本地登录验证报bcrypt非法参数错误问题求助

本地登录时bcrypt参数错误及Cookie未设置问题(部署Heroku正常)

问题描述

开发了一个需输入邮箱和密码的登录界面,用于验证用户存在性及密码匹配性。本地运行(服务器端口3000,前端端口8800)时出现bcrypt参数错误,且access_token Cookie无法设置,但部署到Heroku云服务器后功能正常。

相关代码

import User from "../models/User.js";
import bcrypt from "bcryptjs";
import { createError } from "../error.js";
import jwt from "jsonwebtoken";

export const signin = async (req, res, next) => {
try {
const user = await User.findOne({ email: req.body.email });
if (!user) return next(createError(404, "User wurde nicht gefunden!"));

const isCorrect = bcrypt.compare(req.body.password, user.password);   
if (!isCorrect) return next(createError(400, "Falsches Passwort"));

const token = jwt.sign({ id: user._id }, process.env.JWT);
const { password, ...others } = user._doc;

return res
  .cookie("access_token", token, {
    httpOnly: true,
    maxAge: 7200000,
  })
  .status(200)
  .json(others);
 } catch (err) {
   next(err);
 }
};

错误信息

bcrypt.js:286
nextTick(callback.bind(this, Error("Illegal arguments: "+(typeof s)+', '+ (typeof hash))));
^
Error: Illegal arguments: string, undefined

解决方案

1. 修复bcrypt.compare异步调用问题

bcrypt.compare是异步函数,当前代码未加await,导致isCorrect是Promise对象而非布尔值,直接引发逻辑错误。修改代码:

const isCorrect = await bcrypt.compare(req.body.password, user.password);

2. 排查本地数据库用户密码字段

错误提示Illegal arguments: string, undefined说明user.password为undefined,原因是本地数据库中的用户记录无password字段,或字段值未正确加密存储:

  • 检查本地数据库的用户文档,确认password字段存在且为bcrypt加密后的字符串;
  • 若为手动添加的测试用户,需重新通过注册接口创建(确保注册时已用bcrypt.hash加密密码)。

3. 解决本地跨域Cookie设置问题

本地前后端跨域(端口不同)时,需配置CORS和Cookie参数:

  • CORS配置(以cors包为例):
app.use(cors({
  origin: "http://localhost:8800",
  credentials: true // 允许携带凭证
}));
  • Cookie参数修改:
res.cookie("access_token", token, {
  httpOnly: true,
  maxAge: 7200000,
  sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
  secure: process.env.NODE_ENV === "production" // 本地http环境设为false,生产https设为true
});

注:若本地使用Chrome浏览器,sameSite: "none"要求secure: true,此时需搭建本地HTTPS服务,或改用sameSite: "lax"。

内容的提问来源于stack exchange,提问作者Captai-N

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 10:06:21