我是 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 請求有關,但我不知道我做錯了什么,提前致謝。
uj5u.com熱心網友回復:
此行使用“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"
這就是為什么你永遠不會回到你的索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/325159.html
標籤:javascript Python 烧瓶
