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

JavaScript发送POST请求后Flask重定向未生效问题求助

问题根源

存在两个核心错误:

  • 你在调用xhr.send()后立刻执行了window.location.href = "/addTokens",XHR请求是异步的,调用send后不会等待请求完成就会执行后续代码,跳页会销毁当前页面的JS上下文,轻则POST请求的响应无处理载体,重则请求直接被中断未发送成功。
  • XMLHttpRequest收到后端返回的302重定向响应时,只会在XHR请求链路内部自动跟随重定向拉取目标地址内容,不会触发浏览器顶层页面的地址跳转,所以你能看到后端打印重定向日志,但浏览器页面完全没变化。

修改方案

第一步:修改前端JS代码

删除原代码中紧跟xhr.send()的跳转逻辑,新增XHR请求完成的监听事件,请求成功后前端主动控制页面跳转:

finishBuy.addEventListener('click', () => {
     price = price * 1000000000000000000
     ethereum
    .request({
              // Some code
    })
    .then(
        function (txHash) {
            console.log('Hash: ' + txHash)

            var xhr = new XMLHttpRequest();
            xhr.open("POST", "/addTokens");
            xhr.setRequestHeader('Content-Type', 'application/json');
            // 新增请求完成监听
            xhr.onload = function () {
                if (xhr.status >= 200 && xhr.status < 300) {
                    // 请求成功后跳转到首页,不需要等后端返回重定向
                    window.location.href = "/"
                    // 如果你需要先跳转到checkingPayment页面,就把上面的地址改成"/addTokens"即可
                }
            }
            xhr.send(JSON.stringify({
                hash: txHash
            }));
            // 删掉原来的window.location.href = "/addTokens"
        }
    )
    .catch((error) => console.error);
})

第二步:调整后端POST接口逻辑(可选)

既然跳转交给前端控制,后端POST接口不需要再返回重定向,直接返回成功状态即可,避免无意义的重定向请求开销:

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/addTokens", methods=["GET", "POST"])
def addTokens():
  if request.method == "GET":
        return render_template("checkingPayment.html")
  if request.method == "POST":
        hash = request.get_json()
        print(f"Hash: {hash}")
        print("处理完成")
        # 直接返回200状态即可,不需要redirect
        return {"status": "success"}, 200

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 22:18:00