问题
I am using an $http.post call to my server and sending over some user data:
$http.post('/streamdb/create/',{user:$scope.user.username})
My server then performs a series of operations and retrieves a certain id from the DB. I would like to have the client redirected to the page ('streams/'+id), so I have the operations terminate with a
res.redirect('/streams/'+id)
I could send over the id:
res.json({id:id})
and then respond to a .success() clause with a $location, or window.open (as seen here, or here) but that seems a little wasteful: the server already knows where to send me, why should I make an additional call?
While the server shows that the routing was done, the new page never renders, it just stays on the original page.
Thanks for any help!
回答1:
Your server side code cannot redirect the browser from an ajax response. The only reason that redirecting from the server side works without ajax is you are actually sending a fresh page each time, so a redirect means simply serving a different page. Ajax requests dont get served an entire new page as a response, so you are stuck on the current one. You need to go the 'wasteful' route :) Return the id in the response body and redirect using the angular $location service like you mentioned. I recommend using a promise and performing the redirect once it resolves.
来源:https://stackoverflow.com/questions/19577745/using-http-post-and-res-redirect-without-resolving-the-promise