Express 不同港口的本地护照授权

Express 不同港口的本地护照授权,express,angular,passport.js,express-session,Express,Angular,Passport.js,Express Session,我有一个node.js应用程序在端口5000上运行,我使用passport.js作为授权。我通过post请求授权用户,其中我使用自定义回调: this.router.post('/member/login', (req, res, next) => { passport.authenticate('local', (err, member, info) => { if (err) res.json(400).json({message: "An error

我有一个node.js应用程序在端口5000上运行,我使用passport.js作为授权。我通过post请求授权用户,其中我使用自定义回调:

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);
    });
这很好,但当我开发local时,我有一个前端Angular2应用程序,它运行在不同的端口(4200)上,因此在我的开发中,我无法获得授权用户:req.user未定义。我使用express会话存储授权用户

在部署时,我将两个应用程序捆绑在一起,这样一切都能正常工作


有没有人对这个问题有一个好的简单的解决方案?同样,我只有在开发中才会遇到这个问题。

您可以将这两个服务隐藏在代理之后,例如Nginx。您的两项服务都将使用1个地址

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;
  }
}

所以,所有请求都将转到前端服务,所有请求都将转到后端服务

我认为您存在跨域问题,因为您在不同的端口上运行

这个问题已经讨论过了,我相信您可以在这里找到解决方案:


简言之,您需要将服务器配置为发送适当的标头,以允许跨域共享访问标头。

如果您的web应用程序和API在不同的端口上运行,那么对于使用passport的身份验证,我们可以尝试此方法

  • 在web应用程序(localhost:300)中单击socialAuth按钮后,使用window.open函数直接调用passport API(localhost:5000/auth/google)
  • 身份验证完成后,回调URL将再次命中API端口(localhost:5000/auth/google/callback)
  • 现在在回调中,我们有必须发送到web应用程序(端口3000)的用户信息,使用套接字编程来实现这一点

举个小例子可以提高你答案的质量。这确实是我想要的!非常感谢。为什么这些东西在您的开发环境中不能同时运行?我正在使用Angular 2 cli,不知道是否可以使用自己的节点作为服务器,以及如何设置它。