首页 > 解决方案 > 从 JavaScript 发送 POST 请求后,Flask 未重定向

问题描述

我是 JavaScript 和 http 请求的新手,也许我在这里做错了,希望有人能帮助我。

我正在尝试使用 XMLHttpRequest 向我的烧瓶应用程序发送 POST 请求,这是 JS 代码:

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.send(JSON.stringify({
                hash: txHash
            }));
            window.location.href = "/addTokens"
        }
    )
    .catch((error) => console.error);})

这是我的python代码

@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("Redirecting to index")
        return redirect(url_for('index'))

Flask 打印“重定向到索引”,但浏览器从不重定向到“/”,实际上它什么也没做。

我不想使用 html 表单发布信息,我几乎可以肯定这与我发送的 http 请求有关,但我不知道我做错了什么,在此先感谢。

标签: javascriptpythonflask

解决方案


此行使用“POST”方法发送和 XHR 请求。

xhr.open("POST", "/addTokens");

你在你的服务器上打了这些行:

print("Redirecting to index")
return redirect(url_for('index'))

因此,您发送了一个重定向响应,但是,您不会在 JS 中处理它。(Klaus D 和我打赌,但 XHR 不做重定向)。

然后你做一个'GET'请求返回/addTokens

window.location.href = "/addTokens"

这就是为什么你永远不会回到你的索引。


推荐阅读