不同端口上的本地护照授权
我有一个运行在端口5000上的node.js应用程序,我在其中使用passport.js作为授权.我通过发布请求(在其中使用自定义回调)授权用户:
I have a node.js application running on port 5000, where I use passport.js as authorization. I authorize users from a post request, where I use a custom callback:
this.router.post('/member/login', (req, res, next) => {
passport.authenticate('local', (err, member, info) => {
if (err) res.json(400).json({message: "An error ocurred"});
if (!member) {
console.log("No member found!");
return res.status(409).json({message: "No member found!"})
}
req.logIn(member, (err) => {
if (err) {
console.log(err);
return res.status(400).json({message: "An error ocurred"});
}
return res.json(member);
});
})(req, res, next);
});
这很好用,但是当我在本地开发时,我有一个前端Angular2应用程序,该应用程序在其他端口(4200)上运行,因此在我的开发中,我无法获得授权用户:req.user是未定义的.我使用快速会话来存储授权用户.
This works fine, but when I develop local I have a frontend Angular2 application, which runs on a different port (4200), so in my development I am not possible to get the authorized user: req.user is undefined. I use express-session to store the authorized user.
部署时,我将两个应用程序捆绑在一起,因此一切正常.
When I deploy I bundle both applications up together, so everything works.
有人对此问题有一个好的简单的解决方案吗?同样,只有在开发中,我才遇到这个问题.
Does anyone have a good and simple solution for this issue? Again it's only in development I have this problem.
您可以将两个服务都隐藏在代理(例如Nginx)后面.而且您的两个服务都将使用1个地址.
You can hide both services behind proxy, Nginx for example. And both your services will be use 1 address.
NGINX配置示例
server {
listen 80;
server_name example.com;
proxy_set_header Host $http_host;
proxy_pass_header Server;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
location / {
proxy_pass http://frontend_address:port;
proxy_redirect default;
}
location ~ /api {
proxy_pass http://backend_address:port;
proxy_redirect default;
}
}
因此,所有请求 http://example.com 都将转到前端服务,而所有请求
So all requests http://example.com will go to frontend service, and all requests http://example.com/api/ go to backend service.