Connect Create React App to Express
Connect React to Express. React as the frontend and Express as the backend.
Table of Contents 📖
- What is React?
- What is Express?
- Create a Folder for our Project
- Create a React App with Create React App
- What is npx?
- Running our React Application
- What is npm start?
- Setup our Express App Folder Structure
- Initializing our Express App
- Installing Express and nodemon
- Creating an Express Application
- Adding a Route to our Express Application
- Binding our Express Application to a Port
- Running our Express Application
- Creating a Users Route
- Adding our Router to our Express Application
- Creating a Users React Component
- Displaying our Users Component
- Proxy API Requests to Express
- Requesting Data from our Express Application
- React useState Hook
- Contacting our Express App
- What is componentDidMount?
- What is fetch?
- Displaying our Users
- Summary
What is React?
React is a front-end JavaScript library for building websites and is commonly used for building single page applications.
What is Express?
Express is a back-end framework for Node designed for building websites/web applications.
Create a Folder for our Project
To start, lets first create a folder to hold our project.
mkdir express-and-react
cd express-and-react
Create a React App with Create React App
Now lets use Create React App to create our React application. Create-react-app is a fast way to create a React application as it sets up the development environment for us, allowing us to focus on development without having to learn about build tools (Create React App uses Babel and webpack under the hood).
To use Create React App we need to have Node version 14.0.0 or higher and npm version 5.6 or higher installed, then we just need to run create-react-app using
the package runner tool npx.
npx create-react-app client
What is npx?
The package tool npx stands for Node Package Execute and it comes pre-installed with npm version 5.2.0 and higher. Npx is a npm package runner that allows us to execute any packages from the npm registry without installing it. The command "npx create-react-app client" creates a React project with the environment already set up and places it all inside a folder called client.
Running our React Application
By default, our React application will be running on port 3000. To get our React application started, go into the client directory we made and run npm start.
cd client
npm start
What is npm start?
Npm start runs the node script that is listed under start in the package.json file. Here, this gets our React application up and running on http://localhost:3000.
Setup our Express App Folder Structure
Now, lets create an Express app to work as our backend. To do this, first navigate to the project's top folder and create a folder called server.
Initializing our Express App
Lets now create a separate package.json file in our server folder to keep track of our server side dependencies. To create a package.json file, we use the command npm init. We also want to supply the argument -y to provide all the defaults for setting up our package.json file. Make sure npm init is ran inside the server folder.
cd server
npm init -y
Installing Express and nodemon
Now lets install Express with npm. Express is simply a npm package.
npm install express
We will also install nodemon, a command line interface tool that watches the file system for changes and when it detects a change it restarts the server with our changes. We will install nodemon globally by using -g. This will install nodemon on our system path so we can use nodemon in any future project.
npm install nodemon -g
Creating an Express Application
Now lets create a file called index.js in our server folder and require Express inside it.
After requiring Express, we need to create an Express application. This is done by calling the function returned from require('express'). We will capture this inside a variable called app.
const app = express();
Adding a Route to our Express Application
Lets create a route to handle incoming requests to our Express application at the path /api. Adding /api to the path is not necessary but it shows that we want our Express application to act as an API, giving our React application data and other API related tasks.
app.get('/api', (request, response) => {
response.send('Hello world from Express!');
});
Binding our Express Application to a Port
Lets have our Express application listen for incoming requests on port 1234. This port should be different from the port our React application is listening on. By default, our React application will be listening on port 3000.
app.listen(1234);
Running our Express Application
Lets ensure our Express application is working properly by running our index.js file and then visiting localhost:1234/api.
nodemon index.js
Creating a Users Route
Lets now create a folder called routes within our server folder that will hold a route called users.
Our users.js file will return a JSON array of users that we can then parse in the front end. But first, lets require Express and create a router object.
const express = require('express');
const router = express.Router();
An Express router helps us create better route handlers and organize our code. Lets add a route to this router object that will return a JSON object
containing an array of users. We also need to export this router object to be used in our index.js file.
router.get('/', (request, response) => {
response.json(
[
{
username: 'WittCode',
age: 26
},
{
username: 'Mike',
age: 32
}
]
)
});
module.exports = router;
Adding our Router to our Express Application
Back inside our index.js file where we created our Express app, lets import our router we made and assign it to the path /api/users.
const users = require('./routes/users');
app.use('/api/users', users);
Now, whenever the route localhost:1234/api/users is accessed, that JSON object we created will be returned.
Creating a Users React Component
Now lets create a React component that will send a request to our Express /api/users route, parse the returned data, and display it.
import { Component } from 'react';
class Users extends Component {
render() {
return (
<div>
<h1>Users Component</h1>
</div>
)
}
}
export default Users;
Displaying our Users Component
Inside App.js, lets display our Users component. In the image above, we can see that App.js is located inside client/src/. Remove all the content inside App.js and add the following.
import Users from './components/Users';
function App() {
return (
<Users />
);
}
export default App;
Lets visit our React page again at localhost:3000/ to make sure that our changes worked.
Proxy API Requests to Express
Now lets connect our React and Express application. This is done with the key proxy in our package.json file of our React application. A proxy is a server that is an intermediate between a client requesting a resource and a server providing a response.
"proxy": "http://localhost:1234"
Adding the key proxy tells our React development server to proxy any unknown requests to the URL provided. So here, our React application will proxy requests to our Express application, which is running on port 1234.
Requesting Data from our Express Application
As our React and Express applications are now connected, we can make requests to our Express application from our React application.
To get started, lets add a constructor to our Users component. In this constructor we will keep track of the state of
a variable called users. The variable users will be filled with the users returned from our Express users route.
constructor(props) {
super(props);
this.state = {
users: []
}
}
React useState Hook
We would be using the React useState hook but hooks can only be used in functional components, the component we created here is a class component.
The useState hook is a hook that allows us to have state variables in functional components.
However, in a class component we can keep track of state by setting this.state equal to an object containing variables we want to keep state information of.
Contacting our Express App
Lets fill up our users state variable with the users at our Express users route. We want to contact our Express application's users route after our React component is mounted.
componentDidMount() {
}
What is componentDidMount?
componentDidMount is invoked immediately after a component is inserted into the DOM. Specifically, it is called during the mounting phase of the React Life cycle (after the component is rendered). We want to contact the Express API inside componentDidMount because this ensures our data won't be loaded until after the component is rendered.
After our component has mounted, lets make a request to our Express application's users route by using fetch().
fetch('/api/users')
What is fetch?
Fetch is a Node module that makes it easy for making HTTP requests. The HTTP request we are making here is to our Express application's users route. Fetch returns a promise that is resolved into a response.
fetch('/api/users')
.then(response => );
We then get the JSON data from this response by using the method .json(). This is a method from the JavaScript Response interface that returns a promise.
fetch('/api/users')
.then(response => response.json());
This promise will be resolved into an array containing our users.
fetch('/api/users')
.then(response => response.json())
.then(users => {});
We then change the state of our users state variable to contain the array of users by using the method setState.
fetch('/api/users')
.then(response => response.json())
.then(users => {
this.setState({users: users});
});
Displaying our Users
Now, lets loop through our users array and display the information of each. We will do this inside our React render method.
render() {
return (
<ul>
{this.state.users.map(user => (
<li>Username: {user.username}, Age: {user.age}</li>
))}
</ul>
)
}
Make sure that our Express application is running with "nodemon index.js" and our React application is running with "npm start". Now, when our Express application starts up it should display the following.
Summary
But there we have it! Having React as the frontend and Express as the backend for a website is very powerful. If this video was helpful, please consider donating at the top of the page, sharing this article, and checking out my YouTube channel WittCode!