【问题标题】:Flask not redirecting after POST request sent from JavaScript从 JavaScript 发送 POST 请求后,Flask 未重定向
【发布时间】:2021-10-19 12:00:19
【问题描述】:

我是 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 请求有关,但我不知道我做错了什么,在此先感谢。

【问题讨论】:

  • 浏览器不会在 XHR 上重定向。

标签: javascript python flask


【解决方案1】:

这一行使用 'POST' 方法发送和 XHR 请求。

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

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

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

所以你发回一个重定向响应,但是,你没有在你的 JS 中处理它。 (Klaus D 和我打赌,但 XHR 不做重定向)。

然后您向/addTokens 发出“GET”请求

window.location.href = "/addTokens"

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

【讨论】:

  • 如果我理解正确,flask 服务器正在发送响应,我需要在 JS 中编写重定向代码?
  • 耶。例如,您可以发回一些内容,而不是重定向响应,这些内容将“/”url 作为属性传递给window.location.href。或者,您可以解析响应代码,并相应地设置window.location.href。
猜你喜欢
  • 1970-01-01
  • 2021-09-19
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多