简体   繁体   中英

Redirect to other url after submitting form by post request nodejs

What is wrong in code? Why the redirection to route /result doesn't happening after form submit by post action?

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');
});

form.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>

Use res.redirect("/result") in your form api handler to redirect the frontend.

Since here you are not using AJAX call to submit data but are redirecting the form on submit therefore onClick event is of no use. Either you can use AJAX call to submit form data and then redirect the page or directly use res.redirect() after submission.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM