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

React.js & Node.js登录功能无响应问题求助

登录功能无响应的问题修复方案

前端代码问题及修复

1. 按钮点击事件绑定错误

登录按钮同时绑定了onClick={() => onSubmitForm}和表单的onSubmit={onSubmitForm},前者仅返回函数并未执行,还会和表单提交逻辑冲突。直接移除按钮的onClick属性,保留表单的onSubmit即可:

<Button
  type="submit"
  value="submit"
  // 移除该行:onClick={() => onSubmitForm}
  fullWidth
  variant="contained"
  sx={{ mt: 3, mb: 2 }}
  style={{backgroundColor: "#282c34"}}
>
  Log ind
</Button>

2. Axios请求语法错误

await Axios.post(...)后的.then()写法存在语法问题,导致请求逻辑中断。既然已经使用await,可直接处理响应,无需额外的.then:

const onSubmitForm = async (e) => {
    e.preventDefault();
    try {
        const response = await Axios.post('http://localhost:5000/login', {
            email,
            password,
        });
        console.log("登录响应:", response.data); // 新增日志查看后端返回内容
        // setSuccess(true)
    } catch (err) {
        console.log("登录错误:", err);
    }
};

后端代码问题及修复

1. PostgreSQL占位符使用错误

PostgreSQL的pg模块使用$1、$2作为参数占位符,而非MySQL的?,原查询语句会执行失败:

// 原错误语句
// pool.query("SELECT * FROM users WHERE email = ?", [email], ...)

// 修复后
pool.query("SELECT * FROM users WHERE email = $1", [email], ...)

2. 查询结果与响应逻辑错误

  • pg模块的查询结果存储在result.rows数组中,result.password应改为result.rows[0].password
  • 原代码先执行res.send(result)会提前结束响应,导致后续密码验证结果无法反馈给前端。需先验证密码,再根据结果返回响应:
app.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  try {
    pool.query("SELECT * FROM users WHERE email = $1", [email], (err, result) => {
      if (err) {
        return res.send({ err: err.message }); // 返回错误信息,终止后续执行
      }
      if (result.rows.length > 0) {
        const user = result.rows[0];
        bcrypt.compare(password, user.password, (error, isMatch) => {
          if (error) {
            return res.send({ err: error.message });
          }
          console.log("密码验证结果:", isMatch);
          isMatch 
            ? res.send({ message: "登录成功", user: { email: user.email } }) 
            : res.send({ message: "Wrong email or password" });
        });
      } else {
        res.send({ message: "Wrong email or password" });
      }
    });
  } catch (error) {
    console.log("Something went wrong..");
    res.send({ err: error.message }); // 给前端返回服务器异常信息
  }
});

3. 异常捕获优化

原代码的try/catch无法捕获pool.query回调内的错误,需在回调内处理错误,同时在catch块中给前端返回响应,避免请求挂起。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 17:06:28