Teaching myself how to use a React frontend with a Django server and I'm having difficulty getting the React routes to work properly. Whenever I reload the page it thinks I'm making a GET request to the server. Refreshing at localhost:8000 works fine, but anything other than an API route errors out.
Pretty sure the issue is in one of my urls.py files.
quiz_app/urls.py
urlpatterns = [
path('', include('quizzes.urls')),
path('', include('frontend.urls'))
]
frontend/urls.py
urlpatterns = [
path('', views.index )
]
quizzes/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path(r'^nested_admin/', include('nested_admin.urls')),
re_path('api/quizzes/', views.QuizList.as_view()),
re_path('api/quizzes/<str:name>/', views.SingleQuiz.as_view()),
re_path('api/questions/', views.QuestionList.as_view()),
re_path('api/answers/', views.AnswerList.as_view())
]
For good measure:
frontend/views.py
def index(request):
return render(request, 'frontend/index.html')
frontend/src/App.js
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Grid>
<Header />
<Route exact path="/" component={Quizzes} />
<Route exact path="/:name" component={Quiz} />
</Grid>
</div>
</Router>
)
}
};
To reiterate, the issue is that the "/:name" routes in App.js are attempting to make "GET" requests to the Django server and erroring out because there's nothing to handle them rather than defaulting to a React route. Let me know what I'm doing wrong here. I've fixed this problem when using React with other server frameworks, but I'm new to Python/Django so not sure where to go from here.
If I understand your question correctly, then views.html renders the page that will run the app defined in App.js. And the problem you have is that if you go to a URL http://yourserver/my-quiz, where my-quiz is a quiz name, the request will be sent to the Django server, which says: 404, I don’t know about that URL.
One working solution is to add a catch-all route to your Django main app:
urlpatterns += re_path(r'.*', views.index)
as the last route. This simply makes Django render your app for each and every request, and react-router will take care of the routing.
The downside to this is that you won’t get a 404 if the page really doesn’t exist (in your case, there is no quiz by that name). I haven’t found a solution for that yet except duplicating routing configuration (in your case, checking in the Django app if a quiz with that name exists).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With