首页 > 解决方案 > 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”。

谢谢您的帮助。

标签: javascripthtmlapifetch

解决方案


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

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

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

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


推荐阅读