Untied interface and backend with Django, webpack, reactjs, agent-router

I am trying to separate my interface and my server in my project. My interface consists of reactjs , and routing will be done using react-router , My backend if a Django form has been made, and I plan to use the interface to call the API (ajax) in Django.

Right now, I'm not sure how to get these two ends to talk to each other correctly.

Here is the link to my project

Here is my project structure:

 /cherngloong /app (frontend) /cherngloong /templates index.jtml urls.py settings.py ... /contact urls.py views.py 

I use webpack to create all my JS and CSS and put it in index.html using webpack_loader , which looks like this:

 {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Example</title> </head> <body> <div id="app"></div> {% render_bundle 'main' %} </body> </html> 

In Django here is my cherngloong/urls.py :

 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'', TemplateView.as_view(template_name='index.html')), url(r'^api/', include('contact.urls')) ] urlpatterns += staticfiles_urlpatterns() 

I do not want to serve my application from django or make django to work with the same view on ANY URL.

Here are my react-router routes:

 var routes = ( <Router> <Route path="/" component={ Views.Layout } > <Route path="contact" component={ Views.Contact }/> </Route> <Route path="*" component={ Views.RouteNotFound } /> </Router> ); export default routes; 

Currently I can start the server, but when I start the front end, I see this in the developer tools

 http://localhost:8000/static/public/js/main.js Failed to load resource: the server responded with a status of 404 (NOT FOUND) 
+7
python django reactjs webpack react-router
source share
1 answer

Your settings.py defines the following:

 STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'app'), ) 

This will serve the files in the /app/ directory. therefore url /static/public/js/ translated into the directory /app/public/js/ .

What you want is to serve the files in the /public/ directory. Use the following settings:

 STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'public'), ) WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'js/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json') } } 

In addition, the URLs are different from the code you posted here and on github. url(r'', Templa... will match all urls and just display index.html even when /api/ called. Move this line down:

 urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^api/', include('contact.urls')), ] urlpatterns += staticfiles_urlpatterns() urlpatterns += [ url(r'', TemplateView.as_view(template_name='index.html')), ] 
+4
source share

All Articles