React JS with Express JS: A Comprehensive Guide to Building Modern Web Applications
Introduction
Web fullstack development is constantly growing and the technologies like React JS with Express JS we are using to develop the full stack application. React JS and Express JS are two powerful frameworks where we use React JS to develop the frontend part of the application means which user experience on the browser and we use Express JS to develop server-side programming like Rest API, HTTP server and other required things at the server level. We can develop the full-stack application by combining react with express js.
In this article, We will cover the basic overview of React JS, Express JS and will showcase step-by-step process about how to develop a full-stack application using Express JS with React JS
Setting Up the Development Environment
Prerequisites
Before starting, we have to ensure that we have Node.js and npm (Node Package Manager) installed on your machine. if it’s not installed, please use this article to install Node.js
Installing Node.js and npm
Download and install Node.js from the official website. npm comes bundled with Node.js.
Setting Up a React Project
npx create-react-app tekody-app cd tekody-app
Setting Up an Express Project
mkdir tekody-express-app
cd tekody-express-app
npm init -y
npm install express
npm install cors
Creating a Simple Express Server
Basic Server Setup
In your tekody-express-app
directory, create a file named server.js
and add the following code:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 8000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Handling Routes in Express
You can define more routes in your server.js
:
app.get('/api', (req, res) => {
res.json({ message: 'Hello from the API!' });
});
Middleware in Express
Middleware functions can process requests before they reach your routes. Configure Cors middleware to allow requests from different origins.
app.use(cors());
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
const express = require('express');
const app = express();
var cors = require('cors')
const PORT = process.env.PORT || 8000;
app.use(cors());
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.get('/api', (req, res) => {
res.json({ message: 'Hello from the API!' });
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Start the server
Run the below command
node server.js
After that, you will see this message “Server is running on port 8000” in your console which means your server is running on localhost at 8000 port. Now you can access your API ‘http://localhost:8000/api’ using Postman or any other XHR client and this will return response as shown in below image.
Building a React Frontend
Creating a React App
Use create-react-app
CLI to generate a new React project. This sets up everything you need for a React application.
npx create-react-app tekody-appcd tekody-app
Modify your app.js in src folder with below code
import React, { useEffect } from 'react';
import './App.css';
function App() {
return (
<div className="App">
Tekody React App
</div>
);
}
export default App;
Connecting React with Express JS
Making HTTP Requests from React to Express JS
You can use the fetch
API or a library like Axios to make HTTP requests from your React frontend to your Express backend.
Handling Data Responses in React
Fetch the data from Express Js in your React components using ‘fetch’
useEffect(() => {
fetch('http://localhost:8000/api')
.then(response => response.json())
.then(data => console.log(data));
}, []);
Using Axios for API Calls
To use Axios, let’s install it first with the below command.
npm install axios
then integrate Axios to fetch the data from Express JS API
import React, { useEffect, useState } from 'react';
import axios from "axios";
import './App.css';
function App() {
const [data, setData] = useState('');
useEffect(() => {
axios
.get("http://localhost:8000/api")
.then(function (response) {
setData(response.data);
});
}, []);
return (
<div className="App">
<h1>Tekody React App</h1>
<h2>API Response - {data.message}</h2>
</div>
);
}
export default App;
Basic understanding React JS
What is React JS?
React JS is a popular JavaScript library for building user interfaces, particularly single-page applications where you need a fast, interactive experience. Developed and maintained by Facebook, React allows developers to create large web applications that can update and render efficiently in response to data changes.
Key Features of React JS
- Component-Based Architecture: React breaks down the UI into reusable components, making the code more manageable and scalable.
- Virtual DOM: React uses a virtual DOM to improve performance. It minimizes the number of costly DOM manipulations by efficiently updating the real DOM.
- One-Way Data Binding: Data flows in one direction, making the app more predictable and easier to debug.
- JSX: JavaScript XML allows you to write HTML directly within JavaScript, making the code more readable and easy to write.
Advantages of Using React JS
- Performance: Thanks to the virtual DOM, React applications are fast and responsive.
- Reusability: Components can be reused across the application, reducing redundancy and enhancing maintainability.
- Developer Tools: React comes with a robust set of developer tools that make debugging and performance monitoring easier.
Basic understanding Express JS
What is Express JS?
Express JS is a minimal and flexible Node.js web application framework that provides a robust set of features to develop web and mobile applications. It facilitates the rapid creation of robust APIs and web servers.
Key Features of Express JS
- Routing: Express provides a powerful routing mechanism that allows you to define routes for your application.
- Middleware: Middleware functions in Express can handle tasks such as authentication, logging, and request parsing.
- Template Engines: Express supports various template engines for rendering dynamic HTML pages.
Advantages of Using Express JS
- Simplicity: Its minimalistic nature allows for quick setup and a straightforward learning curve.
- Flexibility: Highly customizable and integrates well with various databases and tools.
- Performance: Built on Node.js, Express inherits its asynchronous, non-blocking nature, leading to high-performance applications.
Why Combine React JS with Express JS?
Benefits of Integrating React with Express JS
Combining React with Express JS allows developers to build full-stack applications. React handles the frontend, providing a dynamic and interactive user interface, while Express manages the backend, handling API requests and server-side logic.
Use Cases for React and Express Integration
- Single Page Applications (SPAs): React’s SPA capabilities are enhanced when paired with Express for backend services.
- Real-time Applications: Combining these tools is perfect for real-time applications like chat apps or live dashboards.
- E-commerce Platforms: They offer the flexibility and performance required for complex e-commerce solutions.
Conclusion
I am wrapping up this article (React JS with Express JS). Hopefully, this will be helpful while you are planning to set up a full-stack application using tech stack React JS with Express JS. we:
- Created a server app using Express JS
- Created one sample API using Express JS
- Created a React app for our frontend
- Made an API call to our server with a combination of React JS with Express JS
- Sent data from our backend to our frontend
Hope, this helped!
Some useful links:
if you are looking for React Js Job Support, please visit this https://tekody.com/services/react-js-job-support/
if you are looking for Angular Js Job Support, please visit this https://tekody.com/services/angular-js-job-support/