[英]Server-side redirect without calling GET twice
I'm trying to implement what is basically a multi-step form: submit page 1 with a POST request, then have the user be redirected to page 2 of the form.我正在尝试实现基本上是一个多步骤表单:使用 POST 请求提交第 1 页,然后将用户重定向到表单的第 2 页。 This ends up making two GET requests (one
fetch
and one document
GET, looking at the network requests), which I'm not sure is right.这最终产生了两个 GET 请求(一个
fetch
和一个document
GET,查看网络请求),我不确定这是否正确。 Why does the initial GET request not just get the HTML page that should be rendered (the response to the fetch
request is empty)?为什么初始 GET 请求不只是获取应该呈现的 HTML 页面(
fetch
请求的响应为空)? Should there actually be two requests in the right pattern for this, or is my understanding of how redirects should work not quite right?实际上是否应该有两个正确模式的请求,或者我对重定向应该如何工作的理解不太正确?
Client code:客户端代码:
fetch("/page-1", {
method: "POST",
redirect: "follow",
<...other params here>
}).then(resp => {
window.location.href = resp.url;
})
Flask server code: Flask 服务器代码:
@app.route("/page-1", methods=["GET", "POST"]
def page_1():
if request.method == "POST":
# save page 1 data here
return redirect(url_for("page-2", _scheme="https", _external=True))
if request.method == "GET":
return render_template("page-1.html")
@app.route("/page-2", methods=["GET", "POST"]
def page_2():
if request.method == "POST":
# save page 2 data here
if request.method == "GET":
# **this code path is called twice every time the user navigates page 1->2
return render_template("page-2.html")
fetch
makes a POST request to /page-1
fetch
向/page-1
发出 POST 请求page-2
instead"page-2
”fetch
follows the redirect and makes a GET request to /page-2
fetch
遵循重定向并向/page-2
发出 GET 请求page-2.html
after passing it through a template enginepage-2.html
的内容fetch
ignores everything about the response except the URL fetch
忽略除了 URL 之外的所有响应location.href
location.href
If you want to process the data with fetch
then call a method like response.text()
and process the response with JavaScript.如果要使用
fetch
处理数据,请调用response.text()
之类的方法并使用 JavaScript 处理响应。
If you want to navigate to the resulting page, then use a regular form submission in the first place.如果您想导航到结果页面,请首先使用常规表单提交。 The point of
fetch
is to make HTTP requests without leaving the current page. fetch
的要点是在不离开当前页面的情况下发出 HTTP 请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.