Why isn't res.redirect actually redirecting me

2019-07-23 15:13发布

I have a basic login controller with a form that updates the $scope of the user. When they click a button the login() function is triggered.

.controller('loginCtrl', ['$scope','$http',function($scope,$http) {

    $scope.user = {
        'username' : "",
        'password' : ""
    };

    $scope.login = function(){
        $http.post('/login', $scope.user).then(function (response){
            console.log(response.data);
        });

    }

}]);

And here is my routing for /login

app.post('/login', function(req,res,next){

    passport.authenticate('local-login', function(err, user, info){
        if (err){
            console.log(err);
            return next(err);
        } else if (!user){
            return res.send(info);
        } else {
            req.logIn(user, function(err){
                if (err){
                    return next(err);
                } else {
                    return res.redirect('/view1');
                }
            });
        }
    })(req,res,next);

});

and here is my passport local-login.

passport.use('local-login', new LocalStrategy({
    passReqToCallback: true // Allows us to pass back the entire request to the callback function
},
function (req, email, password, done){
    // Checks database via mongoose
    ,function (err,user){
        if (err){
            return done(err);
        } else {
            if (!user){
                return done(null, false, { message : 'No user found.'});
            } else if (!user.validPassword(password)) {
                return done(null, false, { message : 'Incorrect password'});
            } else {
                return done(null, user);
            }
        }
    });
}));

The main problem here is when the res.redirect('/view1') is triggered in my routing logic the controller is receiving the html page as the response.data instead of actually being redirected. ($http.post().then(function (response){});)

If this is incorrect how should I actually be handling the redirecting to /view1 after the user has successfully logged in?

1条回答
仙女界的扛把子
2楼-- · 2019-07-23 15:41

As your are calling the backend from javascript, you basically do an ajax call behind scenes, which will not work with redirects and other HTTP Headers.

In order to redirect the user to the correct page, you have to check the HTTP Status code in the response from your backend and redirect the user to the correct site via angular. Which could look something like this:

if(response.status == 302) {
    $window.location.href = '/view1';
}

or instead of sending a redirect you can send a status update from the server like:

res.json({
    success: true,
    redirectTo: '/view1'
});

and parse it on the client:

if(response.data.success){
   $window.location.href = response.data.redirectTo;
}
查看更多
登录 后发表回答