react routing and django url conflict

后端 未结 3 2163
庸人自扰
庸人自扰 2020-12-13 19:59

I am using reactjs as a frontend and django as backend. React router is used for routing. When i refresh the page that has routed by react router, i get django 404 Pag

相关标签:
3条回答
  • 2020-12-13 20:37

    The issue is probably that you haven't configured your URLs to handle the routes that are defined in React Router. In your Django urls.py you should be using a catch all to match all URLs to your index template

    urlpatterns += [
        # match the root
        url(r'^$', base_view),
        # match all other pages
        url(r'^(?:.*)/?$', base_view),
    ]
    

    The base_view would be a view function that renders a template which includes your bundled app.

    0 讨论(0)
  • 2020-12-13 20:38

    In case anyone has this same problem, in django 2.0, follow 'Kevin Martin Jose' answer but instead, replace url with re_path

    from django.urls import path, re_path
    
    urlpatterns = [
        path('login/', LoginView.as_view(), name='login'),
        path('logout/', LogoutView.as_view()),
        path('/', login_required(TemplateView.as_view(template_name="app.html"), 
        login_url='login')),
        re_path(r'^(?:.*)/?$', login_required(TemplateView.as_view(template_name="app.html"), 
        login_url='login')),
    ]
    
    0 讨论(0)
  • 2020-12-13 20:55

    In case someone's wondering, I had the exact problem and Paul S's answer solved it. Adding an answer instead of comment only because SO does not let me format code snippets inside comments. I ended up using a mixture of django's new path() and the old urls() in my urls.py:

    urlpatterns = [
        path('login/', LoginView.as_view(), name='login'),
        path('logout/', LogoutView.as_view()),
        path('/', login_required(TemplateView.as_view(template_name="app.html"), 
        login_url='login')),
        url(r'^(?:.*)/?$',    login_required(TemplateView.as_view(template_name="app.html"), 
        login_url='login')),
    ]
    

    Django handles the login, logout and the root /. React router handles everything else

    0 讨论(0)
提交回复
热议问题