How to resolve Cannot GET /logout in NodeJS, MySQL

Viewed 416

I have a problem, and I can't resolve the Logout function. I've referred to different websites and youtube tutorials, but all I see is about logout for Mongo, etc.

In my "controllers" folder > "auth.js", I have a snippet code for the logout session. Basically, it clears the cookie stored. My register and login function works. The logout, on the other hand, is hard.

//Logout Session for USER
exports.logout = (req,res) => {
    res.clearCookie('jwt');
    res.redirect('shop/login');
};

In my "routes" folder > "user.js", I have this code for logout.

router.get('/profile', (req, res) => {
    if (req.session.login) {
        res.render('shop/profile');
    } else {
        res.send('Please login to view this page!');
    }
    res.end();
});

//LOG OUT 
router.post('/logout',(req, res)=>{
  req.logOut();
  res.redirect("shop/login");
});

And lastly, in "views" folder > "profile.ejs", I have this code.

<div class="container">
    <div class="row">
        <div class="col-sm-8 mt-5">
            <p class="headline2">Welcome!</p>
            <h1><a href="/logout">Log out</a></h1>
        </div>
    </div>
</div>
1 Answers

According to your code, Log Out should be GET request instead of POST.

Please update "routes"> folder> "user.js" as follows:

router.get('/profile', (req, res) => {
    if (req.session.login) {
        res.render('shop/profile');
    } else {
        res.send('Please login to view this page!');
    }
    res.end();
});

//LOG OUT 
router.get('/logout', authController.logout);

Please Make sure you have imported the logout() function

Related