Reputation: 11228
I am using AngularJs with NodeJs.
I have a scenario when upon a successful HTTP POST request, I need to redirect the user.
In the client through AngularJS, I make a HTTP POST request to a route:
$http.post('/aPath', data)
.success(function (result) {
//Handle success
})
.error(function (err) {
//Handle error
});
This route is handled within NodeJs that then does the actual POST. Upon success, within the route handler, I redirect:
function handlePostRequest (req, res) {
//Route handler
//HTTP POST Request
//Following code called when POST request is successful
if (result) {
//Successful post
res.redirect("http://www.google.com");
}
}
However, the browser does not navigate to google. Instead, in the error handler of the POST request within the AngularJS client, the control is reached.
I checked the server and find that the POST request is returned as status code 302 and thus is picked by the error handler for the POST request in the client.
I cannot figure out why, when the server successfully executes the redirect code, the control still reaches the client and that too the error handler. How do I redirect successfully?
Upvotes: 2
Views: 3015
Reputation: 8511
Is it a HTTP POST in angular or an XHR? If it's an XHR you can't redirect the client from serverside, you'd need to send back an error which you then handle in your clientside script such as:
$http({
method: 'POST',
url: 'yoururl',
}).success(function(data, status, headers, config) {
// success stuff
}).error(function(data, status, headers, config) {
if (status == 302) {
window.location = headers('Location');
}
})
Upvotes: 3
Reputation: 6620
Successful XHRs come back with a status of 200. Your server handing back a 302 is technically correct, but it isn't what $http in Angular is expecting. If your server can hand you a 200, you can then do your redirect in the .success function of the $http request.
Upvotes: 0