1

I am writting login system but when i click logout button website is opening same page.

<form action="out" method="POST">
    <button type="submit" class="dropdown-item py-3 pr-5">logout</button>
</form>

server.js:

app.post('/out', function(request, response) {
    request.session.destroy();
    response.redirect('/');
});
app.get('/', function(request, response) {
    if (request.session.loggedin) {
        response.sendFile(path.join(__dirname + '/public/chat.html'));
    } else {
        response.sendFile(path.join(__dirname + '/public/index.html'));
    }
});

Website every time opening chat.html but If I full refresh the site, web site opening index.html.

sayalok
  • 882
  • 3
  • 15
  • 30

1 Answers1

2
app.post('/out', function(request, response) {
    request.session.destroy(err => {
        if(err) {
             console.log(err)
         }else{
             response.redirect('/signup');
         }
    });
});

U can try this. First destroy the session then call a callback function inside there check if there is any issue in destroying session if not then redirect

sayalok
  • 882
  • 3
  • 15
  • 30
  • 1
    This is the right way to do it because `request.session.destroy()` is asynchronous and unless you wait until its done before you redirect, you run the risk of the redirect getting processed by the browser and the new incoming request arrived BEFORE the session has been fully destroyed. – jfriend00 Jan 26 '20 at 07:02
  • yes i forget to mention the `asynchronous ` word Thanks @jfriend00 – sayalok Jan 26 '20 at 07:13
  • I solved. https://stackoverflow.com/questions/6096492/node-js-and-express-session-handling-back-button-problem – Yavuz Selim Özmen Jan 26 '20 at 12:38