This is a very common question among newer React developers, and one question I had when I was starting out with React and Node.js. In this short example I will show you how to make create-react-app
work with Node.js and Express Back-end.
Create a project using create-react-app
.
create-react-app example-create-react-app-express
Create a /client
directory under example-create-react-app-express
directory and move all the React boilerplate code created by create-react-app
to this new client directory.
cd example-create-react-app-express
mkdir client
Create a package.json
file inside the root directory (example-create-react-app-express
) and copy the following contents:
{
"name": "example-create-react-app-express",
"version": "1.0.0",
"scripts": {
"client": "cd client && yarn start",
"server": "nodemon server.js",
"dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
},
"dependencies": {
"express": "^4.16.2"
},
"devDependencies": {
"concurrently": "^3.5.0"
}
}
Notice I am using concurrently
to run the React app and Server at the same time. The –kill-others-on-fail
flag will kill other processes if one exits with a non zero status code.
Install nodemon
globally and the server dependencies:
npm i nodemon -g
yarn
Create a server.js
file and copy the following contents:
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/api/hello', (req, res) => {
res.send({ express: 'Hello From Express' });
});
app.listen(port, () => console.log(`Listening on port ${port}`));
This is a simple Express server that will run on port 5000 and have a single API GET
route /api/hello
.
At this point you can run the Express server with the following command (still inside the root directory):
node server.js
Now navigate to [http://localhost:5000/api/hello](http://localhost:5000/api/hello,)
, and you will get the following:
Now switch over to the client
directory where our React app lives.
Add the following line to the package.json
file created by create-react-app
.
"proxy": "http://localhost:5000/"
The key to using an Express back-end server with a project created with create-react-app
is to use a proxy. This tells the Web-pack development server to proxy our API requests to our API server, given that our Express server is running on localhost:5000
.
Now modify /client/src/App.js
to call our Express API Back-end, changes are in bold.
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
state = {
response: ''
};
componentDidMount() {
this.callApi()
.then(res => this.setState({ response: res.express }))
.catch(err => console.log(err));
}
callApi = async () => {
const response = await fetch('/api/hello');
const body = await response.json();
if (response.status !== 200) throw Error(body.message);
return body;
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">{this.state.response}</p>
</div>
);
}
}
export default App;
We create callApi
method to interact with our Express API Back-end, then we call this method in componentDidMount
and finally set the state to the API response, which will be Hello From Express.
Notice we didn’t use a fully qualified URL [http://localhost:5000/api/hello](http://localhost:5000/api/hello)
to call our API, even though our React app runs on a different port (3000). This is because of the **proxy**
line we added to the package.json
file earlier.
From the project root directory run the following:
yarn dev
This will launch the React app and run the server at the same time.
Now navigate to [http://localhost:3000](http://localhost:3000)
and you will hit the React app displaying the message coming from our Express back-end server. Nice 🎉!
This will be the final project structure.
Get the full code on the GitHub repository.
Thank you for reading and I hope you enjoyed it. Any question, suggestions let me know in the comments below!
You can follow me on Twitter and GitHub.
This post was originally posted on my personal blog website.
Recommended Courses:
Develop React apps and UIs like the pros
☞ https://goo.gl/1Jz7Wk
Build Apps with ReactJS: The Complete Course
☞ https://goo.gl/pU3ii5
Redux JS - Learn to use Redux JS with your React JS apps!
☞ https://goo.gl/YzJ8CC
React JS and Redux - Mastering Web Apps
☞ https://goo.gl/sGtKqe
☞ JavaScript Programming Tutorial Full Course for Beginners
☞ Getting Started with Node.js - Full Tutorial
☞ Learn JavaScript - Become a Zero to Hero
☞ Angular and Nodejs Integration Tutorial
☞ How To Create A Password Protected File Sharing Site With Node.js, MongoDB, and Express