javascript - AngularJS + Django: URL refresh or direct access not loading correctly -
we have angularjs embedded our django application, url routing handled angularjs ui-router. working fine navigating between partials using ui-sref , clicking around within application.
return $stateprovider.state('root.dashboard', { abstract: true, url: 'dashboard/' }).state('root.dashboard.profile', { url: 'profile/', views: { '@': { templateurl: urls['dashboard:profile'](), controller: 'profilecontroller' } } }).state('root.dashboard.home', { url: '', views: { '@': { templateurl: urls['dashboard:dashboard_home'](), controller: 'dashboardcontroller' } } ...
the problem when user has navigated non-root page (say example http://example.com/dashboard/profile/
), , user refreshes browser, re-loads browser's url or pastes in non-root url directly browser. instead of loading page retaining same url in browser, user getting redirected root page (http://example.com/dashboard/
) in case.
since routing handled angular, on server side don't have url routes defined non-root urls; instead have middleware redirects 404s root page:
class redirect404(object): def process_response(self, request, response): if response.status_code != 404 or request.method != 'get': return response return httpresponsepermanentredirect('/dashboard')
we expect router able maintain original url , bring user original page (i.e. 'dashboard/profile
'). note have set html5mode in angular follows:
$locationprovider.html5mode = true;
there mistake in our understanding and/or setup, , appreciate clarification.
we expect router able maintain original url , bring user original page.
that misunderstanding.
here sequence of events:
- the user types
http://example.com/dashboard/profile/
location bar. - the browser sends
get
request server url. - your server responds
301
redirect response. - the browser sees response , sends new
get
requesthttp://example.com/dashboard/
. - the server responds angular page.
- the angular application starts , looks @
window.href
see current route is. sees root route , responds appropriately.
in other words, when redirect lose original url.
the solution simple: instead of redirecting, return page in response (valid) url. way requested url maintained, , when angular starts able figure out right route. (this assumes routing set in angular, sounds have working.)
the implementation simple. change django urls.py
this:
urlpatterns = [ url(r'^dashboard/$', my_view), ]
to this:
urlpatterns = [ url(r'^dashboard/.*$', my_view), ]
Comments
Post a Comment