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-app
Application 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.json
File 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 build
When 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.json
File, if you find it convenient.
In the code below, we requirepath
The 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:
- A simple React application example: Get GitHub user information through API
- Build a simple counter with React
- VS Code setup for React development
- How to pass props to child components through React Router
- Create an application using Electron and React
- Tutorial: Create a spreadsheet with React
- Roadmap for learning React
- Learn how to use Redux
- Getting started with JSX
- Stylized components
- Introduction to Redux Saga
- Introduction to React Router
- Introduction to React
- Reaction component
- Virtual DOM
- Reaction event
- Reaction state
- Reaction props
- Reaction fragment
- React Context API
- Reaction PropTypes
- Reaction Concept: Declarative
- React: How to display other components when clicked
- How to loop inside React JSX
- Props and status in React
- Should you use jQuery or React?
- How much JavaScript do I need to know to use React?
- Gatsby Introduction
- How to reference DOM elements in React
- One-way data flow in React
- React high-end components
- React to life cycle events
- Reaction concept: immutability
- Reaction concept: purity
- Introduction to React hooks
- Introduction to create-react-app
- Reaction concept: composition
- React: demo component and container component
- Code splitting in React
- Server-side rendering with React
- How to install React
- CSS in React
- Use SASS in React
- Processing forms in React
- Reaction strict mode
- Reaction portal
- React rendering props
- Test React components
- How to pass parameters to event handlers in React
- How to deal with errors in React
- How to return multiple elements in JSX
- Conditional rendering in React
- Reaction, how to transfer props to subcomponents
- How to get the value of an input element in React
- How to use useState React hook
- How to use useCallback React hook
- How to use useEffect React hook
- How to use useMemo React hook
- How to use useRef React hook
- How to use useContext React hook
- How to use useReducer React hook
- How to connect your React app to the backend of the same source
- Reaching the router tutorial
- How to use React Developer Tools
- How to learn React
- How to debug a React application
- How to render HTML in React
- How to fix `dangerouslySetInnerHTML` does not match the error in React
- How can I solve the problem of React login form status and browser auto-fill
- How to configure HTTPS in React application on localhost
- How to fix the "Component cannot be updated while rendering other components" error in React
- Can I use React hooks within the conditions?
- Using useState with objects: how to update
- How to move in code blocks using React and Tailwind
- React, focus on an item in React when added to the DOM
- Response, edit text on doubleclick