【问题标题】:How to redirect to html page in passport authentication with Node.js to angularjs如何在使用 Node.js 到 angularjs 的护照身份验证中重定向到 html 页面
【发布时间】:2017-03-23 14:50:35
【问题描述】:

我在 Mean Stack Application 中使用了 passport.js 的 Customcallback。我已经设法从 Angular 控制器和我所做的护照操作中调用了 app.post。

app.controller('LoginCtrl',
 function ($scope, $http, $window, $filter, $location)
 {
     $scope.LoginClick = function () {

         $http.post('/login', $scope.login).success(function(response){

             $location.path('/home.html');

     })
     .error(function(err){
         $scope.error_message = err;
     });
     };
 });

在 server.js 中

app.post('/', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
   if (err) { return next(err); }
   if (!user) { return res.redirect('/'); }
  req.logIn(user, function(err) {
    if (err) { return next(err); }
   return res.redirect('/home.html);
 });
})(req, res, next);
});

但是这里从节点的重定向不起作用以及如何将它们传递给角度控制器。如果它通过身份验证或成功到 home.html 并且如果错误重定向到带有错误消息的登录页面。

谁能帮忙解决。

【问题讨论】:

  • 只需重定向到'/'并在成功登录后需要设置会话/cookie 的角度控制器中进行检查。并始终检查该 cookie 以重定向到 angular 的主页
  • @Love-Kesh 你能用支票的例子解释一下吗?我的意思是从节点到角度的响应来检查
  • 您需要获取登录用户数据以响应登录 api,然后在 cookie 中设置该用户以检查用户是否已登录。用户注销时还需要清除该cookie。
  • 那是passport js处理的吧
  • passport 在节点 js 的服务器端而不是客户端(角度)端处理所有这些。您需要手动操作。

标签: angularjs node.js express passport.js passport-local


【解决方案1】:

在 server.js 中,如果通过身份验证应该返回 200 http 状态码并且什么都不做。

重定向动作应该在 Angular(客户端)上执行,服务器只返回成功或失败。

server.js

app.post('/', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) {
      return next(err);
    }
    if (!user) {
      res.writeHead(401, {'Content-Type': 'application/json'});
      return res.end();
    }
    req.logIn(user, function(err) {
      if (err) {
        return next(err);
      }
      res.writeHead(200, {'Content-Type': 'application/json'});
      return res.end();
    });
  })(req, res, next);
});

【讨论】:

  • 角度如何从节点获取资源以及如何在角度验证成功或失败
  • @charantej 不需要从节点获取资源,$http.post().success() 当服务器返回 2xx http 状态码时运行它,$http.post().error() 当服务器返回不是 2xx http 状态码时运行它。
  • 我也有同样的想法,但它总是运行成功。在控制台中我看到发布 /login 并且状态是 302
  • server.js 应该更新。 NodeJS Docs http_event_response.
猜你喜欢
  • 2018-03-28
  • 2014-06-22
  • 2019-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
  • 2011-07-01
相关资源
最近更新 更多