skip to Main Content

Logout route doesn’t work, even if another route is used, it fails to render or redirect to that route. But the console.log("am clicked"); works

const express = require('express')
const app = express()
const path = require('path')
const fs = require('fs')
const port = 7000
const sqlite3 = require("sqlite3").verbose();
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyparser = require('body-parser');

let fdata = require('./fashion.json');
fdata = fdata.Sheet1;


app.use(session({
  secret: 'keyboardwarrior',
  resave: false,
  saveUninitialized: true,
  cookie: {
      maxAge: 30 * 60 * 1000 // 30 minutes
  }
}));


app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cookieParser());

app.get('/', (req, res) => {
  res.render('shop');
})

app.get('/shop', (req, res) => {
  res.render('shop');
})

app.get('/checkout', (req, res) => {
  res.render('checkout')
})

app.get('/fashion', (req, res) => {
res.send(fdata)
})

// Loggedin
app.get('/loggedin', (req, res) => {
  res.render("shop")
})

// Blank
app.get('/blank', (req, res) => {
  res.render("blank")
})


// Register
app.post('/register', async (req, res) => {
  const {firstname, lastname, usermail, password} = req.body; 
  if (!usermail || !password) return res.status(400).send({error: "Email or password missing."});

  db.serialize(() => {
    db.each('SELECT COUNT(*) as count FROM user WHERE email = ?', [usermail], (err, row) => {
      console.log(row)
      if(err) {
        console.log(err.message);
      } else if(row.count > 0) {
        console.log('there is a match');
      } else {
        db.run('INSERT INTO user (fname, lname, email, pass) VALUES(?,?,?,?)', [firstname, lastname, usermail, password], (err) => {
          if (err) {
            return console.log(err.message);
          }
          console.log("User successfully registered.");
        })
      
        res.redirect('/')
      } 
    }); 
  
  });


})


// const isLoggedIn = (req, res, next) => {
//   if(req.session.currentUser){
//       next();
//   }else{
//       res.redirect("/");
//   }
// };

// app.get("/", isLoggedIn, (req, res) => {
//   res.render("/", {currentUser: req.session.currentUser});
// });


app.get('/user/:id', function(req,res){
  const id = req.params.id;

  db.serialize(()=>{
    db.each('SELECT * FROM user WHERE _id = ?', [id], (err, row) => {     
    
      try {
        console.log(`${row._id}`);
        res.send(row);
      }catch (err) { 
        res.status(400).send(err);
      }
    
    })
  })
});


// login
app.post('/', async (req, res) => {
  const {usermail, password} = req.body; 

  db.serialize(()=>{
    db.each('SELECT _id ID, email USEREMAIL, pass USERPASS FROM user WHERE email = ?', [usermail], (err, row) => {     
      if(err){
        return console.error(err.message);
      }else {
       
        try {
          if(row.USEREMAIL && row.USEREMAIL === usermail) {
            console.log(`${row.ID}`);
            req.session.isLoggedIn = true;
            req.session.currentUser = `${row.USEREMAIL}`;
            res.render('shop', {uid: `${row.ID}`});
          }
        } catch (err) { 
            res.status(400).send(err);
        }

      } 
    })
  })
  
})

app.post('/logout', (req, res) => {
console.log("am clicked");
  if (req.session) {
    req.session.destroy();
    console.log('have been clicked');
  }
  return res.render('shop', {uid: ``});
});

const db = new sqlite3.Database('users.db', err => {
  if (err) {
    return console.error(err.message);
  }
  console.log("Successful connection to the database 'users.db'");
});

app.all('*', (req, res) => {
  res.render('404');
})

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})


Am expecting it to re-render the home route

2

Answers


  1. To fix this, you can modify your logout route as follows:

    app.post('/logout', (req, res) => {
      console.log("am clicked");
      if (req.session) {
        req.session.destroy();
        console.log('have been clicked');
      }
      return res.redirect('/shop');
    });
    
    
    Login or Signup to reply.
  2. Ajax requests made via your client-side Javascript code don’t automatically change anything in the browser. They don’t render content into the browser. They don’t follow redirects and tell the browser to go to a new URL. They JUST return an http status and content back to your Javascript. It is up to your Javascript to do something with the response that is sent back.

    Your client-side code:

    logout.addEventListener('click', () => { 
        axios.post('/logout')
          .then(() => { })
          .catch((err) => { console.log(err) }) 
    });
    

    This code just sends a POST request to your server and then does nothing with the response that comes back from the server. As such the browser completely ignores that response. It doesn’t matter what content you render in the server and send back as the response and it doesn’t matter if you send back a redirect response because your Javascript code is NOT doing anything with whatever response comes back.

    Note, this is different than a <form> POST request. Those responses do not involve your Javascript and there the response is automatically processed by the browser (either redirect or new rendered content).


    If you want the browser to display the contents of a new URL, then you can have the server do a res.redirect(newURL) and you can have your above Javascript check the returned status and if it’s a 3xx response, then it can set window.location to whatever URL is in the Location header. In that way, your Javascript will be telling the browser to go to a new URL and it will then do so.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search