设置Cookie后页面未跳转问题求助:Flask前后端代码排查
我需要实现以下逻辑:当浏览器未设置authcheck Cookie时,跳转至登录页面;已设置该Cookie则直接访问votedummy.html。但执行客户端POST代码后,页面并未跳转至votedummy.html,反而Cookie被返回至服务端,页面停留在原页面。请帮忙排查问题,相关代码如下:
服务端代码
@app.route("/login_endpoint_client", methods=["POST"]) def authtoken(): authtok = request.get_json() print(authtok) data = {"cookie":"value"} resp = requests.post("http://127.0.0.1:8080/vote", json=data) print(resp.text) return authtok
客户端代码
@app.route('/vote', methods=["GET","POST"]) def vote(): if request.method == "GET": cook = request.cookies.get("authcheck") print("cookie",cook) if cook == None: return redirect("http://127.0.0.1:5000/login/API_key1") if cook: return render_template("votedummy.html") if request.method == 'POST': data = request.get_json() resp = make_response(render_template("votedummy.html")) resp.set_cookie("authcheck", data['cookie'], max_age=300) return resp return render_template("vote.html")
核心问题分析
POST请求逻辑被嵌套,永远无法执行
客户端代码中,if request.method == 'POST'的缩进错误,被放在了if request.method == "GET"的代码块内部。当请求为POST时,会直接跳过GET分支的判断,走到最后的return render_template("vote.html"),根本触达不到POST的处理逻辑,自然不会设置Cookie和跳转页面。服务端中转请求导致Cookie无法写入浏览器
服务端的authtoken函数用requests.post调用客户端的/vote接口,这个请求是服务端发起的,而非用户浏览器。客户端返回的Cookie会被服务端的requests库接收,不会写入用户的浏览器,浏览器自然不会跳转,也不会保存Cookie。
修复方案
1. 修正客户端代码缩进
将POST请求的判断移至GET分支外部,与GET同级:
@app.route('/vote', methods=["GET","POST"]) def vote(): if request.method == "GET": cook = request.cookies.get("authcheck") print("cookie",cook) if cook is None: return redirect("http://127.0.0.1:5000/login/API_key1") return render_template("votedummy.html") elif request.method == 'POST': data = request.get_json() resp = make_response(render_template("votedummy.html")) resp.set_cookie("authcheck", data['cookie'], max_age=300) return resp return render_template("vote.html")
2. 调整请求流程
让浏览器直接向客户端的/vote接口发送POST请求,而非通过服务端中转。比如前端登录成功后,用JavaScript直接发起POST请求到http://127.0.0.1:8080/vote,这样客户端返回的Cookie会被浏览器保存,同时页面会跳转到votedummy.html。
内容的提问来源于stack exchange,提问作者himzy

