How to redirect user to a page after receiving the response from a fetch POST request?(接收到 fetch POST 请求的响应后,如何将用户重定向到页面?)
问题描述
我正在为一个使用 fetch() api 向 node.js 服务器发送 POST 请求的 web 应用程序编写代码.在成功的请求服务器以重定向响应时,在 fetch() api 响应正文中接收到此重定向 url.在此之后我应该怎么做才能将用户从 fetch 函数重定向到这个 URL.
I am writing code for a web application that send a POST request to node.js server using fetch() api of javascript. On successful request server responds with a redirection, this redirection url is received in the fetch() api response body. After this what should I do to redirect user to this URL from fetch function.
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.
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.
推荐答案
// 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 POST 请求的响应后,如何将用户重定向到页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:接收到 fetch POST 请求的响应后,如何将用户重定向到页面?
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01