【问题标题】:redirect user from server without client code在没有客户端代码的情况下从服务器重定向用户
【发布时间】:2021-07-25 03:59:17
【问题描述】:

我正在使用 fetch API 向服务器发布请求:

function pay() {

    fetch('/pay', {
        method: 'post',
        redirect: 'follow',
        body: 'data sent'
    })
    .then(response => {
        // I need to redirect user from front-end here using code below
        if(response.redirected) {
            window.location.href = response.url;
        }
    })
    .catch(error => console.log(error));
    
}

然后服务器使用如下重定向响应此请求:

res.redirect(`https://pay.ir/pg/${response.data.token}`);

问题是这个重定向不起作用,我需要从前端重定向用户,就像你在 fetch 函数中看到的那样 window.location.href = response.url;

如何从服务器而不是客户端重定向用户?

【问题讨论】:

    标签: javascript node.js fetch-api


    【解决方案1】:

    这里要记住的重要一点是,重定向意味着“您要求某些东西,但您需要在此 URL 上要求它”。

    这并不意味着“将主浏览器窗口导航到此 URL”。


    如果用户点击一个链接,那么浏览器将请求href 属性中的 URL 并导航到它。如果它收到重定向响应,那么它将导航到那里。

    如果用户触发了一些使用fetch API 的代码,那么浏览器将请求传递给fetch 的URL,并将响应传递给fetch API。如果它得到一个重定向响应,那么它将把响应传递给跟随重定向。 (fetchredirect 选项可能会导致它抛出错误或让作者的 JS 手动处理它)。

    响应无法覆盖浏览器对其的处理并导致导航而不是由fetch API 处理

    【讨论】:

      【解决方案2】:

      当您通过 Ajax 调用访问 api 时,您不能直接将浏览器重定向到另一个 url。
      我能想到的唯一方法是使用表单。

      <form action="/pay" method="POST">
        <label for="fname">First name:</label><br>
        <input type="text" id="fname" name="fname" value="John"><br>
        <label for="lname">Last name:</label><br>
        <input type="text" id="lname" name="lname" value="Doe"><br><br>
        <input type="submit" value="Submit">
      </form> 
      
      <p>If you click the "Submit" button, the form-data will be sent to a page called "/pay" 
      and it will follow through with the redirect response sent by the server.</p>

      OR 否则您必须将 URL 返回到前端并使用 window.location.href='/somepath' 从前端重定向

      【讨论】:

        猜你喜欢
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        • 2017-03-05
        • 2018-03-19
        • 2014-06-09
        • 1970-01-01
        相关资源
        最近更新 更多