javascript - 从 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 请求有关,但我不知道我做错了什么,在此先感谢。
解决方案
此行使用“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"
这就是为什么你永远不会回到你的索引。
推荐阅读
- ios - iOS 版 Google 地方信息 3
- laravel - 不显示用户头像
- python - 如何调试异步 aiohttp 缓慢
- javascript - 如何优雅地使用 v-model 和 Vuex store?
- ios - 我不想快速更新 admob 横幅广告
- azure - 如何使用 go 从 Azure 队列订阅接收消息
- forms - ASP.NET MVC 登录后如何使用用户的数据
- mysql - 通过比较 SQL 中的 2 行进行过滤
- python - NetworkX read_dot 不继承属性
- html - 如何在 select 中内联选项标签并使用 optgroup 划分它们?