ste9206
ste9206

Reputation: 1892

TypeError: req.session.destroy is not a function - Express.js

I've made my webapp using React.js and Express.js as a web-server. React is connected to Express with this (for now) in package.json:

  "proxy": "http://localhost:5000/"

and in my Express server I've used this to handle sessions:

const cookieSession = require('cookie-session');

and this:

app.use(cookieSession({
 name: 'parse-session',
 secret: "SECRET_SIGNING_KEY",
 maxAge: 15724800000
}));

so when I use login to my API it works ok and this is the code to check if currentUser exist:

    return new Promise((resolve,reject)=>{

if(req.session.token){    

    console.log(req.session.token);
    request({

      uri:'http://myserver.herokuapp.com/parse/users/me',
      headers: {
        'X-Parse-Application-Id': 'my-app-id',
        'X-Parse-Session-Token': req.session.token
      },
      json:true    

    }).then((userData) => {

       if(userData){    

          resolve(userData);

       }

    }).catch((error) => {

        reject(error);
    });
  }

and it works without problem, with this call in React:

   fetch('/user',{credentials:'include'})
    .then((response)=>{
        return response.json();
    })
    .then((body)=>{
        if(body.user){
            this.setState({logIn:true});
        }

    }).catch((error)=>{
           console.log('My error:',error);

    });

The problem is when I try to logout: I do this on React:

 axios.post('/logout').then((res)=>{
        console.log(res);

 }).catch((err)=>{
        console.log(err);
 });

and this is logout on Express:

app.post('/logout',(req,res)=>{


if(req.session){

   req.session.destroy((error)=>{
      if(error){
        console.log(error);
      }
   });
}
}); 

that gives to me this error message:

TypeError: req.session.destroy is not a function

why? I've seen that destroy() is a function. I've also tried to put :req.session = null but, when you call after the promise to check if session exist it currently alive.

Why? How could I use to solve it?

Thanks

Upvotes: 5

Views: 8533

Answers (2)

Rob
Rob

Reputation: 338

If you're using cookieSession, then the correct way would be to route to /logout, and from there:

router.get('/', (req, res, next) => {
    if (req.session) {
        req.session = null;
        res.redirect('/');
    } else {
        res.redirect('/login');
    }
});

If you're using express-session, req.session.destroy would work instead.

Upvotes: 0

YasharF
YasharF

Reputation: 642

req.session.destroy is the call to use if you are using express-session npm module. However, you are using cookie-session which in its current version does not define req.session.destroy resulting in the error that you are getting.

To destroy the session while using cookie-session , you just need to set it to null: req.session = null. If you decide to use express-session instead, then req.session.destroy would work.

References:

Upvotes: 21

Related Questions