简体   繁体   English

服务器端重定向,无需调用 GET 两次

[英]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")
  1. fetch makes a POST request to /page-1 fetch/page-1发出 POST 请求
  2. The server responds saying "You need to get page-2 instead"服务器响应说“您需要改为获取page-2
  3. fetch follows the redirect and makes a GET request to /page-2 fetch遵循重定向并向/page-2发出 GET 请求
  4. The server responds with the content of page-2.html after passing it through a template engine服务端通过模板引擎返回page-2.html的内容
  5. fetch ignores everything about the response except the URL fetch忽略除了 URL 之外的所有响应
  6. Your JavaScript assigns the URL to location.href您的 JavaScript 将 URL 分配给location.href
  7. The browser navigates to that URL, making a GET request to get the content to do so浏览器导航到 URL,发出 GET 请求以获取内容

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM