UPDATEExpress会话属性区分
我认为这是值得一提的我正在运行在端口4200,我的服务器在端口8080上运行难道这是一个问题的角度CLI?这是目前我能想到的唯一的事情
当我拨打我的路由'/ auth/login'时,我在会话对象上设置了一个loggedIn属性。要检查用户是否已通过身份验证,则会向“/ auth/checktoken”发出请求。在这里,我检查req.session对象上是否存在loggedIn属性。当我在Postman中执行这些请求时,一切正常,但在使用浏览器时,我的session.loggedIn属性是未定义的。我将粘贴下面的相关代码。在此先感谢您的帮助
服务器端
router.get('/checktoken', (req, res) => {
if(!req.session.loggedIn) {
return res.status(401).send({
userTitle: 'Not authorised',
userMessage: 'You are not authorised to view this'
})
}
return res.status(200).send()
})
客户端
@Injectable()
export class CheckAuthenticationService implements CanActivate {
constructor(
private router: Router,
private http: HttpClient) { }
canActivate() {
this.http.get('http://localhost:8080/auth/checktoken', { responseType: 'text' })
.toPromise()
.then(() => {
this.router.navigate(['admin']);
})
.catch(() => {
this.router.navigate(['login']);
});
return true;
}
}
片段的登录代码设置的loggedIn属性
if (user) {
user.comparePassword(password, (err, isMatch) => {
if (isMatch && isMatch) {
req.session.loggedIn = user;
res.status(200).send()
} else {
res.status(404).send({
userTitle: 'Wrong password',
userMessage: 'Please make sure your password is correct'
});
}
});
}
会话存储设置
app.use(session({
name: 'jack-thomson',
secret: SECRET_KEY,
saveUninitialized: false,
resave: true,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}))
这邮差的所有作品,但打在客户端上这些端点时,.loggedIn是不确定的,总是
我试过:(是的,我在我的节点服务器中使用CORS中间件 – Jackthomson
哟需要在每个请求中添加这个,以下是我的中间件使用的一小部分,如果它可以帮助你'app.use (CORS({ \t起源: 'HTTP://本地主机:4200', \t凭据:真 })); app.use(会话({ \t名称: 'connect.sid', \t仅Http: true, \t secret:process.env.SESSION_KEY, \t resave:false, \t saveUninitialized:true, \t商店:新的MongoStore({mongooseConnection:mongoose。连接}) });' –
谢谢你,但它根本不起作用:/我不知道它是否与我的服务器运行在角度应用程序的不同端口上。角度应用程序运行在端口4200和我的服务器运行在8080 – Jackthomson