3

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.

1
  • 1
    What do you mean by same host and port -- do you mean something like example.com and example.com/api? Commented Jan 25, 2017 at 22:34

1 Answer 1

6

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/

Sign up to request clarification or add additional context in comments.

1 Comment

But why is it better to run react app and for example flask backend on the same port during development?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.