How to connect your React app to the backend of the same source

How to serve React and server-side backend applications from the same source without having to use CORS on the server and worry about ports

I think the most common way to start a React application is to usecreate-react-app. Very convenient.

One problem you might encounter is how to connect it to a backend you already have, or you might want to create one.

In development

When developing an application, you want to take advantage of hot reloading and all other convenient features of create-react-app. How do you combine it with the backend without having to use CORS on the server and worry about the port?

I will provide an example of using Express in the post, but this applies to any other framework.

Assuming you are testing, let's create a React application:

npx create-react-app testing

then

cd testing

Now, create a simple Express server in the server.js file, and you can add it to any location you want. It can even be placed entirely in a separate folder.

If you choose to add this file tocreate-react-appApplication code, run:

npm install express

We are ready to go. Add this simple Express setup:

const express = require('express');
const app = express();

app.get(’/hey’, (req, res) => res.send(‘ho!’))

app.listen(8080)

The key point here: openpackage.jsonFile and add this line somewhere:

"proxy": "http://localhost:8080"

This tells React to proxy API requests to the Node.js server built with Express.

Use nownode server.js. In another window, you use to launch the CRA applicationnpm start.

When the browser opens on port 3000 (by default), open DevTools and run:

fetch('/hey')

If you check the network panel, you should get a successful response in the following ways:ho!information.

in · Production

In production, you will want to runnpm run buildWhen you are ready to deploy, we will use the Express server to serve these static files.

The entire agent is now useless (and will not work in production, this is to simplify development). This means you can keep it inpackage.jsonFile, if you find it convenient.

In the code below, we requirepathThe built-in Node module, we tell the application to provide a static build of the React application:

const express = require('express')
const path = require('path')
const app = express()

app.use(express.static(path.join(__dirname, ‘build’)))

app.get(’/ping’, (req, res) => { return res.send(‘pong’) })

app.get(’/’, (req, res) => { res.sendFile(path.join(__dirname, ‘build’, ‘index.html’)) })

app.listen(8080)

Download mine for freeResponse Handbook


More response tutorials: