登录我的Yii2 + angularjs页面时,我使用用户数据创建cookie:
$jwt = JWT::encode(array(1,2,3), 'myKey123')
setcookie('myData', $jwt, time() + 3600);
我想在我的nodejs + express应用程序中访问它-在处理请求之前,我必须检查用户是否未更改“ myData” cookie。我现在是这样的:
app.use(cookieParser());
app.get('/*', function (req, res, next) {
if(req.cookies.myData) {
jwt.verify(req.cookies.myData, 'myKey123', function(err, decoded) {
if(err)
res.sendStatus(403);
else
return next();
});
} else {
res.sendStatus(403);
}
});
如果登录后直接在浏览器中调用expressjs route,则应用会看到Cookie。
问题:如果通过发出$ http.get()请求来调用route,则expressjs应用程序看不到任何cookie。
Yii2和expressjs在相同的IP上运行,但是在不同的端口上运行,但是我读过,不同的端口不应该是原因,应该吗?我一直在设置不同的Cookie参数,但似乎无济于事。我将不胜感激,谢谢您!
最佳答案
所以我知道现在出了什么问题-在我的$ http.get()请求中,我根本没有设置withCredentials:true。当直接在浏览器中“发出”请求时,默认情况下会传递cookie,但是当通过$ http.get()进行请求时,我必须设置额外的参数,例如:
$http.get(myService('myRoute'), {
params: {
param1: 1,
param2: 2
},
withCredentials: true
}).then(function(response) {
$scope.returnedData = response.data;
});
资料来源:AngularJs documentation for $http requests
withCredentials-{boolean}-是否在XHR对象上设置withCredentials标志。有关更多信息,请参见带有凭据的请求。
关于node.js - Express js无法看到Cookie,该Cookie是在调用route之前设置的,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43873335/