MERN Technology is the most popular trend these days.MERN contains MongoDB, Express, React, and Nodejs With the help of MERN developers can create a fully functional application with a single language (e.g. javascript). Connecting the back end to the front end is the next step toward making a full application. In this article, we will focus on the connectivity of the front end with the backend. We will Render the data from the backend to React(UI).
Requirement
Understanding of express, a little bit of React knowledge(useState,useEffect)hooks.
and Lots of excitement for coding
1. The Folder Setup🤠
Create a folder where we can create two separate folders one for the backend and another for frontend
2. The Backend folder🤓
terminal Requirement
npm init -y
for creating the local server with express.
npm i cors
Cross-Origin Resource Sharing in Node. js is a mechanism by which a front-end client can make requests for resources to an external back-end server.
2. 1 Create a local server
Create a server.js file inside the backend folder
Let's Depp dive into code
//local server
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json())
const port = 5000;
app.get('/home',(req,resp)=>{
resp.json({Name:"Hello i am from backend"})
});
app.listen(port,()=>{
console.log(`Server is runing on port ${port}`);
})
The express.json()
middleware is responsible for parsing incoming requests with JSON payloads. It enables the application to receive JSON data from the request body and convert it into a JavaScript object for easier manipulation and processing.
When app.use(cors())
is called, it enables CORS for all routes of the Express application, allowing the server to respond to cross-origin requests. CORS middleware adds the necessary headers to the HTTP response to indicate that cross-origin requests are allowed. This allows browsers to make requests from one domain to another.
That's it from the backend side😀
Now we have to render this data to react😬
2. The Frontend folder
terminal Requirement
npx create-react-app frontend
This will create a default react app
You do not need to do anything with this default app
2. 1 Create a new component (MyComponent.js)
Learn first these two hooks
import {useEffect,useState} from 'react'
const MyComponent = () =>{
const[data,setData] = useState([]);
useEffect(()=>{
fetch('http://localhost:5000/home')
.then((response)=>response.json())
.then((data)=>setData(data.Name))
.catch(Error =>{
console.log('Error',Error)
})
},[]);
return(
<div>
<h3>{data}</h3>
</div>
)
}
export default MyComponent;
fetch('
http://localhost:5000/home
')
sends an HTTP GET request to the specified URL "http://localhost:5000/home".
The fetch
function returns a Promise that resolves to the response from the server. We can then call the .json()
method on the response to parse the JSON data. Finally, we can handle the retrieved data in the second .then()
callback function or handle any errors in the .catch()
callback function.
In the App.js file, you need to import this component and remove the default return statement with this component
App.js component
import {React} from 'react';
import MyComponent from './MyComponent';
const App = () => {
return (
/////////////////////// Remove this Default ///////////
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Edit src/App.js and save to reload. </p>
<a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a>
</header>
</div>
/////////////////////// Remove this Default ///////////
);
} export default App;
Updated App.js
import {React} from 'react';
import MyComponent from './MyComponent';
const App = () => {
return (
<MyComponent />
);
};
export default App;
and that's it now run the react app with
npm start
You can see that the URL of react is 3000 and backend data is now on react. We did it Now you can easily manipulate this data as you want because React
does a lot of things
Thank you for reading my content. Be sure to follow and comment on what you want me to write about next
🤓