问题
I have a multi-step Angular.js form for signup that saves all the users input into:
$scope.user = {};
Then I use ng-submit
like so:
<form class="css-form" name="myForm" ng-submit="signup()" novalidate>
The Signup function then makes a POST request to my Node.JS API on the /signup
route like so:
$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);
});
};
Note: The above successfully registers a new user and saves the data within MongoDB.
The Issue:
I am using Passport.Js server side to authenticate & register users. I am using the local-signup strategy.
The problem is that if the user is successfully registered they should be automatically redirected to a specific page and the same if they are unsuccessful. Below is my server side code:
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
}));
The issue is that on BOTH successfully registration & unsuccessful it does not redirect the user based on the routes provided. It sends back the actual redirected pages code within the response data. So on successful registration it should send the user to the profile & to the main page if unsuccessful
I can't seem to solve this, maybe my whole technique is wrong. Any help will be appreciated.
回答1:
Not shure, but it might help.
In Angular:
$scope.signup = function(){
return $http.post('/signup',$scope.user)
.then(function(data) {
location.replace(data.redirectUrl); // use appropriate function to update route
});
};
In 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: '/' });
}
);
来源:https://stackoverflow.com/questions/35725074/http-post-passport-js-redirect