[Fixed]-AngularJS + Django: URL refresh or direct access not loading correctly

9๐Ÿ‘

โœ…

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),
]

Leave a comment