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

Next.js登录后无法跳转至/dashboard页面的问题求助

Next.js登录表单跳转失败问题排查与修复

核心问题

登录按钮嵌套在<form>标签内,点击时会触发浏览器表单默认提交行为(页面刷新),导致handleLogin中的异步请求未执行完成页面就已刷新,跳转逻辑失效,控制台日志也因页面刷新被清空。

修复方案

方法1:在登录函数中阻止默认行为

修改handleLogin函数,接收事件参数并调用preventDefault():

const handleLogin = async (e: React.MouseEvent<HTMLButtonElement>) => {
  e.preventDefault(); // 阻止表单默认提交
  try {
    const response = await fetch("/api/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username: username.trim(), password: password.trim() }),
    });

    if (response.status === 200) {
      const data = await response.json();
      setMessage("Login successful");
      router.push(data.redirect);
    } else {
      setMessage("Invalid credentials");
    }
  } catch (error) {
    console.error("Error:", error);
  }
};

保持按钮的onClick绑定不变:

<button
  className="btn text-white bg-gradient-to-r from-blue-500 to-teal-400 hover:bg-teal-700 w-full py-2 rounded-lg"
  onClick={handleLogin}
>
  Log In
</button>

方法2:利用表单onSubmit事件(更符合语义)

修改<form>标签,添加onSubmit事件阻止默认行为并触发登录:

<form onSubmit={(e) => {
  e.preventDefault();
  handleLogin();
}}>

将按钮类型改为submit:

<button
  type="submit"
  className="btn text-white bg-gradient-to-r from-blue-500 to-teal-400 hover:bg-teal-700 w-full py-2 rounded-lg"
>
  Log In
</button>

验证方式

修复后:

  • 浏览器控制台的Network标签可查看/api/login请求的状态和返回值
  • API中的console.log会输出在启动Next.js的终端窗口,而非浏览器控制台,之前你可能找错了日志位置

额外优化

  • 登录成功后可清空提示信息:setMessage(""),避免跳转回登录页时残留提示
  • 添加加载状态,防止重复提交:比如设置isLoading状态,按钮点击后禁用直到请求完成

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:53:22