【问题标题】:How to redirect user to a page after receiving the response from a fetch POST request?接收到 fetch POST 请求的响应后,如何将用户重定向到页面?
【发布时间】:2019-06-22 04:08:57
【问题描述】:

我正在为一个使用 fetch() api 向 node.js 服务器发送 POST 请求的 web 应用程序编写代码。在成功的请求服务器以重定向响应时,在 fetch() api 响应正文中接收到此重定向 url。在此之后,我应该怎么做才能将用户从 fetch 函数重定向到这个 URL。

fetch("/events/registration", {
          method: "POST",
          redirect:"follow",
          headers: {
            "Accept": "application/json , text/plain ,*/*",
            "Content-type": "application/json"
          },
          body: JSON.stringify({
            name,
            email,
          })
        })
.then((res)=>res.json())
.then((data)=>{console.log(data);if(data.err)alert(data.err);Response.redirect()});

作为响应,我在 fetch api 中收到 redirect:true , url: "LinkOfRedirection/redirect",现在我应该怎么做才能将用户从这里重定向到 LinkOfRedirection/redirect。

【问题讨论】:

标签: javascript node.js redirect fetch


【解决方案1】:
// Sets the new location of the current window.
window.location = res.url;

// Sets the new href (URL) for the current window.
window.location.href = res.url;

// Assigns a new URL to the current window.
window.location.assign(res.url);

// Replaces the location of the current window with the new one.
window.location.replace(res.url);

// Sets the location of the current window itself.
self.location = res.url;

// Sets the location of the topmost window of the current window.
top.location = res.url;

或者你可以使用

res.redirect(301, res.url);

【讨论】:

  • 有没有办法从 fetch api 本身重定向用户
  • fetch api 没有重定向默认方法。请参考这个developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  • @VishnuR 当我设置 window.loaction=res.url 如何传递数据?我正在重定向到仪表板,所有需要在仪表板中绘制的数据应首先从数据库中获取,否则仪表板将不显示任何内容。
【解决方案2】:

一个简单的解决方案是这样的:

fetch('/api/login/' , { 方法:'POST', 标题:{ '内容类型':'应用程序/json', 'X-CSRFToken' : csrf, },

    body : JSON.stringify(data)
}).then(result => result.json())
.then(response => {
    
    if(response.status == 200){
        window.location.href = '/'
    }
    else{
        alert(response.message)
    }

})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    • 2013-09-20
    • 1970-01-01
    • 2019-05-26
    • 2021-10-16
    • 1970-01-01
    • 2017-12-27
    相关资源
    最近更新 更多