首页 > 解决方案 > 通过post请求nodejs提交表单后重定向到其他url

问题描述

代码有什么问题?/result为什么通过 post 操作提交表单后不会重定向到路由?

index.js

router.get('/form', (req, res) => {
    res.sendFile(path.join(__dirname, 'form.html'));
});

router.post('/form', (req, res) => {
    console.log('Submitted');
    res.send('Submitted');
});

router.get('/result', (req, res) => {
    res.sendFile('results Page');
});

表单.html

<script type="text/javascript">
    function redirect() { window.location.href='http://localhost:5000/result';}
</script>
<form action="/form" method="post">
    <input type="text" name="name" placeholder="Name">
    <a href="/result">
        <input type="submit" name="form" onClick="redirect()")>
    </a>
</form>

标签: javascriptnode.js

解决方案


res.redirect("/result")在您的表单 api 处理程序中使用以重定向前端。

由于在这里您没有使用 AJAX 调用来提交数据,而是在提交时重定向表单,因此 onClick 事件没有用。您可以使用 AJAX 调用提交表单数据,然后重定向页面,也可以在提交后直接使用 res.redirect()。


推荐阅读