简体   繁体   English

收到来自 fetch POST 请求的响应后,如何将用户重定向到页面?

[英]How to redirect user to a page after receiving the response from a fetch POST request?

I am writing code for a web application that send a POST request to node.js server using fetch() api of javascript.我正在为一个 Web 应用程序编写代码,该应用程序使用 javascript 的 fetch() api 向 node.js 服务器发送 POST 请求。 On successful request server responds with a redirection, this redirection url is received in the fetch() api response body.在成功请求服务器以重定向响应时,此重定向 URL 将在 fetch() api 响应正文中接收。 After this what should I do to redirect user to this URL from fetch function.在此之后,我应该怎么做才能将用户从 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()});

In response that i receive in fetch api I am getting redirect:true , url: "LinkOfRedirection/redirect" , now what should i do to redirect user from here to the LinkOfRedirection/redirect.作为我在 fetch api 中收到的响应,我收到了redirect:true , url: "LinkOfRedirection/redirect" ,现在我应该怎么做才能将用户从这里重定向到 LinkOfRedirection/redirect。

// 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;

Or you can use或者你可以使用

res.redirect(301, res.url);

A simple solution to this would be something like this:一个简单的解决方案是这样的:

fetch('/api/login/' , { method : 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken' : csrf, }, fetch('/api/login/' , { method : 'POST', headers:{ 'Content-Type':'application/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)
    }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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