Harkirat Saluja
Harkirat Saluja

Reputation: 8114

Real URLS with Single Page Applications?

I was using react router for one of my projects, so react is frontend library and routes are managed by react router and backend views are in django and apis in django rest

So i was going through the react-router documentation and I came across this:-

Configuring Your Server Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /accounts/23 your web server will get a request to /accounts/23. You will need it to handle that URL and include your JavaScript application in the response.**

I was wondering how would this work with django views.

Upvotes: 4

Views: 1394

Answers (1)

C14L
C14L

Reputation: 12558

On the development server, you simply set up a route for everything that doesn't start with api/ or static/ to return your basic app.html file. Example

class AppHTMLView(View):

    def get(self, request):
        fn = os.path.join(settings.BASE_DIR, "app", "app.html")
        with open(fn, 'r') as fh:
            return HttpResponse(fh.read())

And on your production server, you configure Nginx accordingly. Something like this

...
location / {
    root /var/www/example.com/static_files/;
    try_files '' /app.html =404;
}

But that's not in any way specific to React, but common to all single page apps.

Upvotes: 3

Related Questions