You need to enable JavaScript to run this app. Flask登录接口redirect返回302、render_template无跳转问题求解
优惠活动
大模型
产品
解决方案
定价
更多

Flask登录接口redirect返回302、render_template无跳转问题求解

问题原因

你的问题核心是前端通过Fetch/XMLHttpRequest等异步方式提交登录表单,而非使用原生HTML form标签的默认提交逻辑:

  • 异步请求收到后端返回的302重定向响应时,浏览器只会自动跟随重定向请求新地址的内容,不会主动替换当前页面
  • 异步请求收到后端返回的render_template生成的HTML内容时,也不会主动把当前页面替换为收到的HTML,因此页面始终停留在登录页
    另外日志里出现了带密码参数的GET请求,属于严重的安全隐患,说明你的前端还存在默认表单提交未阻止、或参数误拼接至URL的问题。
修复方案

你可以任选以下两种方案之一修改:

方案1:改用原生表单提交(最简单)

  • 前端去掉自定义的JS提交逻辑,使用原生form标签提交:
<form method="POST" action="/login">
  <input type="email" name="email" required>
  <input type="password" name="password" required>
  <button type="submit">登录</button>
</form>
  • 后端修改参数取值逻辑,适配原生表单的application/x-www-form-urlencoded格式:
@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == "POST":    
        # 把request.json改成request.form
        email = request.form.get('email')
        password = request.form.get('password')
        print("email: "+email)
        print("password: "+password)
        if(check_user(email, password)):
            print("tries to redirect")
            return redirect(url_for('account'))
        else:
            print("Connection failed")
            return render_template("pages/home.html", title_message="Error", body_message="Incorrect username or password")
    return render_template("pages/accounts/login.html")

方案2:保留异步提交,前端手动处理跳转

  • 后端修改返回格式,不再直接返回页面或重定向,改为返回JSON格式的跳转标识:
from flask import jsonify
@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == "POST":    
        x = request.json
        email = x['email']
        password = x['password']
        if(check_user(email, password)):
            return jsonify({"status": "success", "redirect_url": url_for('account')})
        else:
            return jsonify({"status": "error", "redirect_url": url_for('home', title_message="Error", body_message="Incorrect username or password")})
    return render_template("pages/accounts/login.html")
  • 前端异步请求的回调逻辑里手动跳转页面:
// 以Fetch为例
fetch('/login', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({email: 邮箱输入值, password: 密码输入值})
}).then(res => res.json()).then(data => {
  // 手动跳转到后端返回的地址
  window.location.href = data.redirect_url
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 20:45:06