简体   繁体   中英

req.session returns undefined in the next POST request after is defined

I'm working with a back-end made with Node.js and front-end made with Angular. I use express-sessions for login, at first, it returns the correct req.session.usuario . But in the next POST request for checking if the user is logged in it returns undefined.

Here is the app.js of node

var express = require('express');
var path = require('path');
var logger = require('morgan');
var cors = require('cors');
var session = require('express-session');
var cookieParser = require('cookie-parser');


var indexRouter = require('./routes/index');
var authRouter = require('./routes/auth');
var usersRouter = require('./routes/users');
var instructorRouter = require('./routes/instructor');

var app = express();


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(cors( {
  credentials: true,
  origin: 'http://localhost:4200'
}));
app.use(session({
    secret: "Shh, es un secreto",
    resave: false,
    saveUninitialized: true
    
}))

app.use('/', indexRouter);
app.use('/auth', authRouter);
// app.use('/usuario', authMiddleware.estaLogueado ,usersRouter);
app.use('/usuario', usersRouter);
app.use('/instructor', instructorRouter);

...

module.exports = app;

This is my function for the route in the auth.js


router.post('/login', (req, res, next) => {
    const username = req.body.username.toLowerCase();
    Usuario.findOne({
        where: {
            username: username
        }
    }).then((usuario) =>{
        if (usuario) {
            bcrypt.compare(req.body.password, usuario.password, function(errp, result) {
                if(result){
                    req.session.usuario = usuario.id; // Saves the session
                    console.log("La sesion " + req.session.usuario);
                    res.json({username: usuario.username, color: usuario.color});
                } else {
                    next(new Error("Contraseña incorrecta"));
                }
            });
        }else{
            next(new Error("Usuario invalido"));
        }
    }, err => {
        next(new Error("Usuario invalido: " + err));
    });
});

And this is the function that I use for checking if is logged in:

router.post('/logged', (req, res) => {
    console.log("intento: " + req.session.usuario) // here it shows undefined
    req.session.usuario ? res.json({loggedIn: true}) : res.json({loggedIn: false});
})

In Angular these are the two functions that I use, the first one is the login (which works) and the second one is the logged that returns false all the time:

login(user, pass)  {
    return this.http.post(server + '/auth/login', 
        {username: user, password: pass},
        {withCredentials: true}
    )
}

logged(){
    return this.http.post(server + '/auth/logged', {withCredentials: true})
}

In the actual component I do:

this.authservice.logged().subscribe( (data) => {
    this.loggedIn = data['loggedIn'];
    console.log(data['loggedIn']);
});

What is the problem here?

I finally got the answer, I was doing everything ok but the second request was actually not including the withCredentials json as options, it was passed as body so I added empty brackets to simulate the body and now it works like a charm!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM