Express会话属性区分浏览器和邮递员

UPDATE

我认为值得一提的是我正在运行在端口4200上运行的Angular CLI,而我的服务器在端口8080上运行。这可能是一个问题吗? 这是我现在唯一能想到的事情

当我打电话给路由'/ auth / login'时,我在会话对象上设置了一个loggedIn属性。 要检查用户是否已通过身份validation,请求“/ 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属性的login代码片段

 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是不确定的,总是

我终于弄清楚发生了什么事情。 我的Angular CLI在4200上运行,我的服务器运行在一个单独的端口上。 我用快递服务我的应用程序已经解决了这个问题,所以这都是一条路线。 这已经解决了我的问题。 如果有人来这,我希望这个信息对你来说很方便!

你在使用CORS吗?

我有同样的问题,我通过在每个请求{ withCredentials: true }作为可选参数来解决它。 我的意思是每当你在你的服务中发送一个http / https请求,把这个作为最后一个参数,你就可以走了。

你可以阅读这个和这个 Stackoverflow问题的主题的更多信息。