0

I am currently building a django-react web apps, I am wondering how do I handle my 404 error on react-router and not with django side, this is my code which 404 error will be routed on django server side...

urlpatterns = [
path('admin/', admin.site.urls),
re_path(r'^api/', include(urls)),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
                      document_root=settings.MEDIA_ROOT)


routes = getattr(settings, 'REACT_ROUTES', [])
# urlpatterns += [url(r'^', 
TemplateView.as_view(template_name='index.html'))]
urlpatterns += [url(r'^(%s)?$' % '|'.join(routes),TemplateView.as_view(template_name='index.html'))]
frmbelz
  • 973
  • 9
  • 19
luvwinnie
  • 419
  • 6
  • 17

2 Answers2

2

This is how I would have done:

First define a url from django with regex pattern which accepts anything:

url(r'^.*$', TemplateView.as_view(), name="home")  # This is the view which servers the react application

And add this path at the bottom of the urlpatterns.

Second, add new router in React App:

<Route component={NotFoundComponent} />  // This component is for showing 404 page.

For rest of the routers should have exact.

You can see this tutorial on how to implement 404 page in react.

ruddra
  • 40,233
  • 7
  • 54
  • 78
  • i have tested your solution , but it doesn't route to my react-router 404 error page. it shows my home page for example suppose localhost:8000 is my home page component , when i tried localhost:8000/1 it doesn't route to my component instead it give me 200 status code and showed my home page. [18/Dec/2018 06:41:39] "GET /5 HTTP/1.1" 200 2374 [18/Dec/2018 06:41:39] "GET /static/js/main.67b00170.chunk.js HTTP/1.1" 304 0 [18/Dec/2018 06:41:40] "GET /api/ HTTP/1.1" 200 93 – luvwinnie Dec 18 '18 at 06:42
  • my react component is below
    – luvwinnie Dec 18 '18 at 06:44
  • I think you need to use exact here. Check this SO answer: https://stackoverflow.com/questions/49162311/react-difference-between-route-exact-path-and-route-path – ruddra Dec 18 '18 at 06:46
  • thank you so much, i have been able to make my 404 error routes on react-router, it seems like my django rest api need to request with make sure of the link end with '/' – luvwinnie Dec 18 '18 at 09:23
0

Instead using url() in URL patterns use re_path.

from django.urls import path, re_path

from . import views
from django.views.generic import TemplateView

urlpatterns = [
    re_path('', TemplateView.as_view(template_name="frontend/index.html")),
    # match all other pages

]

This is easiest way to solve this issue.

sagar
  • 1