Node JS redirection after submiting a form

2019-04-12 01:01发布

问题:

I have a html form for my node app and if it gets submitted it shows /code and the text but nothing more and i can't redirect to my Mainpage. How can i redirect after it gets submitted with a Timer to another page? I tried to do it in app.post and clientsided but its not working

<form action="/code" method="post" >
<fieldset>
<input type="text"  name="code"  id="code"
style="text-align: center" 
placeholder="Enter Code" /> <br> <br> <input
type="submit" class="btn btn-success" name="submit" id="submit" 
value=" authentifizieren " />
</fieldset>
</form>

App.js

app.post('/code', function(req, res) {


    var code = req.param("code");

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('Code: '+code+');
    res.end();
});

I just want to redirect from app.post /code back to my mainpage or any other website.

回答1:

Redirects in Node JS:

res.writeHead(302, {
  'Location': 'http://example.com/'
});
res.end();

If you want to do it client-side, in Node JS:

res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Code: '+code);
res.write('<script>setTimeout(function () { window.location.href = "http://example.com/"; }, 5000);</script>');
res.end();


回答2:

res.writeHead(200, {'Content-Type': 'text/html'});
res.write('Code: '+code);
res.write('<script>setTimeout(function () { window.location.href = "http://example.com/"; }, 5000);</script>');
res.end();