Reputation: 413
I am new to React.JS and using react-create-app to setup the project.
I am wondering is there a way to use the same host and port to response for API requests, (the server serves both front-end and back-end, like in Django).
The doc mentions about this but does not go into details.
By same host and port I mean I only need one terminal and run npm start once.
Upvotes: 3
Views: 4904
Reputation: 4913
If there is only for development you can simply add
"proxy": "http://localhost:8000/"
to your package.json
.
This will proxy your API queries from React to your other app working on another port (there 8000).
After you finish, you need to build production code (npm build
command), which result is an index.html
which loads builded js and css bundles.
From Django you need only point your IndexView to this file (you can do this as TemplateView, but maybe simpler is only render like there:
class IndexView(View):
def get(self, request):
index = open(str(settings.BASE_DIR.path('build/index.html')), 'r')
return HttpResponse(content=index.read())
Then only use your API from React - from this point both will work on common port.
Back to development mode - you can also configure your Webpack to build your app everytime you save changes and only run them from Django (or Rails, or Node, or whatever is your backend), but I prefer to use proxy, which keep both apps in their native contexts until you finish development. One disadventage of this solutions is that you need always run both apps simultaneously.
Some usefull info and soultions about this I found there: https://www.fullstackreact.com/articles/using-create-react-app-with-a-server/
Upvotes: 6