Flask在JavaScript发送POST请求后没有重定向



我是JavaScript和http请求的新手,也许我在这里做了一些非常错误的事情,希望有人能帮助我。

我正在尝试使用XMLHttpRequest向我的flask应用程序发送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请求有关,但我不知道我做错了什么,提前感谢。

这一行使用'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"

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

最新更新