如何通过 fetch 在 POST 之后重定向页面

How to redirect page after POST by 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>

这是我的代码,其中我 POST 数据来自 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'.

感谢您的帮助。

当您单击提交按钮时,它会触发 JS,但是当 fetch 异步发出 HTTP 请求时 表单正常提交 。这会触发导航并取消 JS.

您需要防止点击提交按钮的默认行为。

register = async (clickEvent) => {
    clickEvent.preventDefault();

注意:一般应该绑定到表单上的提交事件而不是提交按钮的点击事件。

试试看

register = async() => {
   window.location.href = `${website_url}/client/components/login/login.html`
   // your code
}