[英]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.我正在使用由 Node.js 制成的后端和由 Angular 制成的前端。 I use express-sessions for login, at first, it returns the correct req.session.usuario
.我使用 express-sessions 登录,首先,它返回正确的req.session.usuario
。 But in the next POST request for checking if the user is logged in it returns undefined.但是在下一个用于检查用户是否登录的 POST 请求中,它返回未定义。
Here is the app.js of node这是node的app.js
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这是我的 function 用于 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:这是我用来检查是否已登录的 function:
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:在 Angular 中,这是我使用的两个函数,第一个是登录(有效),第二个是始终返回 false 的日志:
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!我终于得到了答案,我一切正常,但第二个请求实际上不包括 withCredentials json 作为选项,它作为正文传递,所以我添加了空括号来模拟正文,现在它就像一个魅力!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.