【问题标题】:How to redirect after a fetch() function如何在 fetch() 函数后重定向
【发布时间】:2026-01-20 00:35:01
【问题描述】:

我想在 fetch() 函数之后将用户重定向到新网页。我使用 facebook 登录按钮,当用户通过身份验证时,我想将他重定向到包含他的数据的新页面。所以我想知道最好的方法是什么。

我认为 window.location + 一个会话变量可以工作,但我很确定还有比这种方法更正确的方法,比如在 then() 函数之后的重定向函数。

我厌倦了使用 fetch().then().redirect() 但它不起作用,我想做的是类似 ...().redirect(function(userDatas, url){.. .});

    //this is inside the facebook connection function
          fetch('/connect',options).then(function(response){
              response.json().then(function(value){
                window.location = 'http://localhost:3000/fight.html';
                console.log(value);
              });
                
     //after this function, I would like to go to this fight.html page

所以我希望用户在 FB 连接到他的数据后到达fight.html 页面。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    你做错了。您在 response.json() 的响应上调用 .then() 而不是主承诺链。试试:

    fetch('/connect',options)
        .then(function(response) {
            return response.json();
        })
        .then(function(value) {
            window.location = 'http://localhost:3000/fight.html';
            console.log(value);
        });
    

    【讨论】:

    • 谢谢你的回答,无论如何它看起来更干净,但你知道我如何以其他方式重定向用户而不是使用 window.location 因为我需要传递值变量中的数据.我想我可以在 url 中添加数据,但这并不安全
    • 您可以使用本地存储或 cookie。如果 URL 对请求是唯一的,您可以生成一个哈希并将其传递到 URL 中,并将与该哈希关联的响应存储在 localstorage 中,以便在页面加载时可以检索它。有很多方法可以实现它。
    【解决方案2】:

    这应该可以正常工作:

    window
      .fetch('/connect', options)
      .then(response => response.json())
      .then(value => {
        console.log(value)
        window.location = 'http://localhost:3000/fight.html'
      })
    

    【讨论】:

    • 谢谢,是的,它可以工作,但我想我会使用 express-session 模块来传递我的数据
    【解决方案3】:

    来自 html 的元标记可能会。要了解更多 html 中的元标记,请转到 https://www.tutorialspoint.com/How-to-redirect-from-an-HTML-page

    document.write('<meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />'); //if client side
    response.end('<meta http-equiv = "refresh" content = "2; url = https://www.tutorialspoint.com" />'); //if server side
    

    我希望我为你解决了这个问题。如果我没有回复,我会再试一次:)

    【讨论】: