Establishing Communication Between the Frontend and Backend
To connect the frontend (React app) with the backend (Express.js), you need to establish communication between them. Here's how you can achieve that:
In your React app, use the
fetch
API to send HTTP requests to the backend. This allows you to make GET, POST, PUT, DELETE, and other types of requests.Here's an example of sending a GET request to fetch data from the backend:
JAVASCRIPT
1fetch('/api/data')
2 .then(response => response.json())
3 .then(data => {
4 // do something with the data
5 console.log(data);
6 })
7 .catch(error => {
8 // handle the error
9 console.error(error);
10 });
In your Express.js backend, set up API routes to handle the requests. You can define routes for different HTTP methods and specify the logic to execute when a request is received.
Here's an example of handling a GET request in Express.js:
JAVASCRIPT
1app.get('/api/data', (req, res) => {
2 // retrieve data from the database or perform any other operation
3 const data = [
4 { id: 1, name: 'John Doe' },
5 { id: 2, name: 'Jane Smith' }
6 ];
7
8 // send the data as a response
9 res.json(data);
10});
xxxxxxxxxx
29
// Establishing communication between the React app and the Express.js backend
// In your React app, use the `fetch` API to send HTTP requests to the backend
// Example: Sending a GET request to fetch data from the backend
fetch('/api/data')
.then(response => response.json())
.then(data => {
// do something with the data
console.log(data);
})
.catch(error => {
// handle the error
console.error(error);
});
// In your Express.js backend, set up API routes to handle the requests
// Example: Handling a GET request
app.get('/api/data', (req, res) => {
// retrieve data from the database or perform any other operation
const data = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
// send the data as a response
res.json(data);
});
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment