React/ReactJS: A Simple ReactJS + Node.js/Express.js Application Example

In this tutorial, we do a simple ReactJS + Node.js application. A basic function component in React will make a GET request to the Node.js server and display the response.

reactjs expressjs server start

We create a basic Express.js server to run at port 3001 (since port 3000 will be used by React). It sends out an emoji ('😍') in object format for an HTTP request (at its port 3001). Save it as server.js.

					
						const express = require("express");
						const app = express();
						const port = 3001;

						app.get("/", function(req, res) {
						  res.send({"emoji": "😍"}); 
						});

						app.listen(port, () => {
						  console.log(`server is running at port ${port}`);
						});
					
				

Start the terminal and navigate to this node project directory. Start the server by typing sudo npm start into it. Access localhost at this port http://localhost:3001/ and you will see the below page.

reactjs expressjs server start

We next create a function component in React and make use of the built-in fetch() method for making API request to the Node.js file server.js.

					
						import { useState, useEffect } from "react";

						const App = () => {
						  const [emoji, setEmoji] = useState('');

						  useEffect(() => {
						    fetch("http://localhost:3001", { mode: 'cors'})
						      .then(res => res.json())
						      .then(data => setEmoji(data.emoji));
						  },[]);

						  return (
						    <h1>{emoji}</h1>
						  )

						}

						export default App;
					
				

If you start React (sudo npm start), you might encounter the following error.

reactjs nodejs cors error

This is CORS error, occuring due to the browser's adherence to same-origin policy. We add an additional line to server.js (line 6) to allow the above CORS request.

					
						const express = require("express");
						const app = express();
						const port = 3001;

						app.get("/", function(req, res) {
						  res.set('Access-Control-Allow-Origin', 'http://localhost:3000');
						  res.send({"emoji": "😍"}); 
						});

						app.listen(port, () => {
						  console.log(`server is running at port ${port}`);
						});
					
				

The React component will now be rendered fine.

reactjs nodejs connection example

For the above CORS error, there is a Node.js package called cors to use with Express.js to enable CORS requests. Import cors to server.js (line 2) and use (line 5).

						
							sudo npm install --save cors
						
					
						
							const express = require("express");
							const cors = require("cors");
							const app = express();
							const port = 3001;
							app.use(cors());

							app.get("/", function(req, res) {
							  res.send({"emoji": "😍"}); 
							});

							app.listen(port, () => {
							  console.log(`server is running at port ${port}`);
							});