登录到我的 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路由,应用程序会看到cookie。
问题:如果通过发出 $http.get() 请求来调用路由,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} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
关于node.js - Express js看不到cookie,它是在调用route之前设置的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43873335/