decoupled frontend and backend with Django, webpack, reactjs, react

I am trying to decouple my frontend and my backend in my project. My frontend is made up of reactjs and routing will be done with react-router , My backend if made form Django and I plan to use the front end to make API (ajax) calls to 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 build all my JS and CSS and place it into index.html with 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 are 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 don't want to serve my app from django or make django to serve 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;

I can currently run the server but when I run the front end portion, 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)

Your settings.py defines the following:

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

This will serve the files in /app/ directory. so the url /static/public/js/ translates to the /app/public/js/ directory.

What you want is to serve the files in the /public/ dir. 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')
    }
}

Also, the urls are different in the code you posted here and in github. The url(r'', Templa... will match ALL urls and just render index.html even when making calls to /api/ . Move this line to the bottom:

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')),
]
链接地址: http://www.djcxy.com/p/88524.html

上一篇: 使用PHP创建PDF的最佳方式

下一篇: 通过Django,webpack,reactjs等解耦前端和后端