【问题标题】:$http POST & Passport.Js Redirect$http POST & Passport.Js 重定向
【发布时间】:2016-06-13 23:58:05
【问题描述】:

我有一个用于注册的多步骤 Angular.js 表单,它将所有用户输入保存到:

$scope.user = {};

然后我像这样使用ng-submit

<form class="css-form" name="myForm" ng-submit="signup()" novalidate>

然后,Signup 函数在 /signup 路由上向我的 Node.JS API 发出 POST 请求,如下所示:

$scope.signup = function(){

  return $http.post('/signup',$scope.user).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.log("this is the error " + data);
    });
};

注意:以上成功注册了一个新用户,并将数据保存在MongoDB中。

问题:

我正在使用 Passport.Js 服务器端来验证和注册用户。我正在使用 local-signup 策略。

问题是,如果用户注册成功,他们应该被自动重定向到一个特定的页面,如果他们不成功,也是一样的。 以下是我的服务器端代码:

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect : '/profile', // redirect to the secure profile section
        failureRedirect : '/', // redirect back to the signup page if there is an error
        failureFlash : true // allow flash messages
    }));

问题在于,在成功注册和不成功的情况下,它都不会根据提供的路由重定向用户。它在响应数据中发回实际的重定向页面代码。因此,在成功注册后,如果不成功,它应该将用户发送到个人资料和主页

我似乎无法解决这个问题,也许我的整个技术都是错误的。 任何帮助将不胜感激。

【问题讨论】:

    标签: javascript angularjs node.js passport.js


    【解决方案1】:

    不舒尔,但它可能会有所帮助。

    在 Angular 中:

    $scope.signup = function(){
      return $http.post('/signup',$scope.user)
        .then(function(data) {
            location.replace(data.redirectUrl); // use appropriate function to update route
        });
    };
    

    在nodejs中:

       app.post('/signup',
          passport.authenticate('local-signup', { failWithError: true }),
          function(req, res, next) {
            // success
            return res.json({ redirectUrl: '/profile' });
          },
          function(err, req, res, next) {
            // error
            return res.json({ redirectUrl: '/' });
          }
       );
    

    【讨论】:

    • 非常感谢您的回答。这非常有效。您是否知道这种方法涉及的任何风险或者它是否安全?
    • 没有任何风险:这是通过 xhr 请求进行身份验证的标准方式
    • 感谢您的帮助。被困在这几天了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2018-06-02
    • 2015-09-07
    • 2014-12-09
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多