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

如何解决登录用户时出现的UnhandledPromiseRejectionWarning赋值错误

问题解决:登录时无限加载并抛出ReferenceError

嘿,这个问题一眼就能揪出根源!你遇到的UnhandledPromiseRejectionWarning: ReferenceError: Invalid left-hand side in assignment错误,完全是赋值运算符用错了导致的。

先看你signin函数里的这段问题代码:

const cookieOptions = {
  expires: new Date( Date.now() = process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000 ),
  httpOnly: true
}

这里的Date.now() = ...是试图把计算结果赋值给Date.now()的返回值,但函数调用的返回值是一个临时值,不能作为赋值的左值(简单说就是不能给它赋值),这直接违反了JS语法规则,导致代码报错中断,进而让登录请求卡住无限加载。

修正后的完整signin函数

只需要把等号=改成加号+,用来计算当前时间加上cookie过期的毫秒数即可:

exports.signin = (req, res) => {
  try {
    const {email, password} = req.body;
    if(!email || !password) {
      return res.send("<script> alert('Provide an email and/or Password'); window.location='/signin'; </script>");
    }
    con.query('SELECT * FROM users WHERE email = ?', [email], async (error, results) => {
      console.log(results);
      if(!results || !(await bcrypt.compare(password, results[0].password))) {
        return res.send("<script> alert('Email or Password is incorrect'); window.location='/signin'; </script>");
      } else {
        const id = results[0].id;
        const token = jwt.sign({ id }, process.env.JWT_SECRET, { expiresIn: process.env.JWT_EXPIRES_IN });
        console.log("The token is: " + token);
        const cookieOptions = {
          // 将=替换为+,正确计算cookie过期时间
          expires: new Date( Date.now() + process.env.JWT_COOKIE_EXPIRES * 24 * 60 * 60 * 1000 ),
          httpOnly: true
        }
        res.cookie('jwt', token, cookieOptions);
        res.status(200).redirect("/profile");
      }
    });
  } catch(error) {
    console.log(error);
  }
}

补充说明

这个错误大概率是你复制代码时的手滑失误,毕竟视频里的原代码肯定是用加号来计算未来过期时间的。修正后,cookie的过期时间能正常生成,登录流程就能完整执行,不会再卡在加载状态啦。

内容的提问来源于stack exchange,提问作者Star-Lord

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:50:49