【发布时间】:2021-10-16 14:29:35
【问题描述】:
我正在从有效的客户端向后端发送注册数据。我在 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”页面上。我什至不知道如何从 fetch 中的第二个 then 到 console.log(data),因为单击“注册”后我会立即登陆“http://localhost:3000/register”。
感谢您的帮助。
【问题讨论】:
标签: javascript html api fetch