javascript - POST后如何通过fetch重定向页面
问题描述
我正在从有效的客户端向后端发送注册数据。我在 MongoDB 中看到我的数据,所以没关系。但是在单击“注册”按钮后,我想重定向到其他页面“/client/components/login/login.html”并且重定向不起作用。我的FORM
标签看起来像这样:
<form action="http://localhost:3000/register" method="POST">
<div>
<label for="register">Login</label>
<input type="text" id="login" name="login" class="login" required>
</div>
<div>
<label for="password">Password</label>
<input type="password" id="password" name="password" class="password" required>
</div>
<div>
<label for="password2">Repeat Password</label>
<input type="password" id="password2" name="password2" class="password2" required>
</div>
<!-- <button type="submit" id="post-btn">Register</button> -->
<input id="post-btn" type="submit" value="Register">
</form>
这是我通过以下方式发布数据的代码fetch
:
register = async () => {
let url = 'http://localhost:3000/register';
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'manual',
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
if (data.success) {
window.location.href = data.url;
} else {
document.getElementById('message').textContent = data.message
window.location.href = data.url;
}
})
.catch(err => {
document.getElementById('message').innerHTML = err
});
};
document.getElementById('post-btn').addEventListener('click', register);
从后端我收到这样的数据:
{"success":true,"message":"User has been created","url":"/client/components/login/login.html"}
我在谷歌上搜索可以发生重定向,window.location.href
但它没有发生,点击“注册”后,我在“http://localhost:3000/register”页面上。我什至不知道如何console.log(data)
从第二个then
进入,fetch
因为单击“注册”后,我立即登陆“http://localhost:3000/register”。
谢谢您的帮助。
解决方案
当您单击提交按钮时,它会触发 JS,但在fetch
异步发出 HTTP 请求时,表单会正常提交。这会触发导航并取消 JS。
您需要防止单击提交按钮的默认行为。
register = async (clickEvent) => {
clickEvent.preventDefault();
注意:通常应该绑定到表单上的提交事件,而不是提交按钮的点击事件。
推荐阅读
- pdf - 从pdf中删除包括边框的表格数据
- elasticsearch - 碎片作为一个展示
- java - 无法在模拟器中运行工作 apk:InflateException:二进制 XML 文件第 12 行:二进制 XML 文件第 2 行:膨胀类错误
- python - 如何在启动前添加启动参数以存储变量
- facebook - 抓取公开的 Facebook 帖子
- android - 访问 OnKeyListener 内部类中的数组
- spring-boot - 在 Spring Boot 中-您可以在不进行任何解析/干预的情况下进行接收整个消息正文的请求映射吗?
- jsf - 如何手动将 HTTP 请求转发到默认 Faces Servlet
- javascript -
- mysql - MYSQL: can BULK select can still return array of results from inputs of same value?