AngularJS + Django: URL refresh or direct access not loading correctly

后端 未结 1 899
孤独总比滥情好
孤独总比滥情好 2021-01-01 19:35

We have AngularJS embedded into our Django application, with URL routing handled by AngularJS ui-router. All is working fine navigating between partials using ui-sref and cl

相关标签:
1条回答
  • 2021-01-01 19:57

    We expect that the router would be able to maintain the original URL and bring the user back to the original page.

    That is the misunderstanding.

    Here is the sequence of events:

    1. The user types http://example.com/dashboard/profile/ into the location bar.
    2. The browser sends a GET request to the server for that URL.
    3. Your server responds with a 301 redirect response.
    4. The browser sees that response and sends a new GET request to http://example.com/dashboard/.
    5. The server responds with your Angular page.
    6. The Angular application starts up and looks at window.href to see what the current route is. It sees the root route and responds appropriately.

    In other words, when you redirect you lose the original URL.

    The solution is simple: instead of redirecting, simply return your page in response to any (valid) URL. That way the requested URL is maintained, and when Angular starts up it will be able to figure out the right route. (This assumes that routing is set up properly in Angular, but it sounds like you have that working.)

    The implementation is also simple. Just change your Django urls.py from something like this:

    urlpatterns = [
        url(r'^dashboard/$', my_view),
    ]
    

    to something like this:

    urlpatterns = [
        url(r'^dashboard/.*$', my_view),
    ]
    
    0 讨论(0)
提交回复
热议问题