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

Next.js自定义Express服务端登录重定向失效问题求助

解决Next.js + Express登录后重定向无效的问题

你遇到的问题核心在于:用fetch发送AJAX登录请求时,后端的res.redirect('/')不会触发浏览器跳转——因为fetch是异步请求,它只会接收后端的响应,不会自动执行页面跳转操作。下面是具体的解决方案:

问题原因

当你直接用浏览器提交表单(不通过fetch)时,后端的res.redirect会告诉浏览器跳转到新地址;但fetch属于AJAX请求,浏览器会在后台处理这个请求,不会主动改变当前页面的URL,所以后端的重定向指令对它无效。

修复方案

我们需要让后端返回登录状态的通知,然后由前端主动执行跳转:

1. 修改Express后端(server.js)

验证通过后,返回一个JSON格式的成功响应,而不是直接重定向:

app.post('/log_in', (req,res) => {
  console.log(`login form data`);
  console.log(`Username : ${req.body.username}`);
  console.log(`password : ${req.body.password}`);
  
  if(req.body.username === "user" && req.body.password === "123"){
    // 返回登录成功的JSON响应
    res.status(200).json({ success: true, message: '登录成功' });
  } else {
    // 登录失败时返回401状态码和错误信息
    res.status(401).json({ success: false, message: '用户名或密码错误' });
  }
})

2. 修改Next.js前端(Login.js)

在fetch请求的响应中判断登录状态,使用Next.js的路由工具主动跳转:

注意:如果你的Login是类组件,需要用withRouter高阶组件包裹;如果是函数组件,直接使用useRouter钩子。

// 类组件示例:
import React from 'react';
import { withRouter } from 'next/router';

class Login extends React.Component {
  state = { username: '', password: '' };

  async handleSubmit(event) {
    event.preventDefault();
    const { username, password } = this.state;
    try {
      const response = await fetch('/log_in', {
        method: 'post',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, password })
      });

      const data = await response.json();
      if (response.ok) {
        // 登录成功,跳转到根路径
        this.props.router.push('/');
      } else {
        // 处理登录失败,比如提示用户
        alert(data.message);
      }
    } catch (error) {
      console.error('请求出错:', error);
    }
  }

  // 输入框状态更新逻辑
  handleInputChange = (field, value) => {
    this.setState({ [field]: value });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input 
          type="text" 
          value={this.state.username} 
          onChange={(e) => this.handleInputChange('username', e.target.value)}
          placeholder="用户名"
        />
        <input 
          type="password" 
          value={this.state.password} 
          onChange={(e) => this.handleInputChange('password', e.target.value)}
          placeholder="密码"
        />
        <button type="submit">登录</button>
      </form>
    );
  }
}

// 用withRouter包裹类组件,获取router对象
export default withRouter(Login);

额外建议

登录成功后,别忘了在Express端保存用户的登录状态(比如用express-session),这样后续在Next.js的getServerSideProps或API路由里,可以验证用户是否已登录,阻止未授权访问受保护的页面。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:25:44