Integrating React with Express.js
To connect the frontend React app with the backend Express.js API, we need to establish communication between them.
One common approach is to make HTTP requests from the frontend to the backend API endpoints. Express.js makes it easy to define API endpoints using its routing system.
For example, let's say we have a route for retrieving users data from the backend API:
1app.get('/api/users', (req, res) => {
2 // Logic to retrieve users data from the database
3 // Send the users data as a response
4 res.json({
5 users: [
6 { id: 1, name: 'John Doe' },
7 { id: 2, name: 'Jane Smith' }
8 ]
9 });
10});
In this example, when a GET request is made to the /api/users
endpoint, the Express.js server will execute the provided callback function, which retrieves the users data and sends it as a JSON response.
On the frontend side, we can use libraries like axios
or the built-in fetch
API to make HTTP requests to the backend API.
Here's an example of how we can fetch the users data from the backend API using axios
in a React component:
1import axios from 'axios';
2
3const OurComponent = () => {
4 axios.get('/api/users')
5 .then(response => {
6 // Handle the response and update the component state
7 })
8 .catch(error => {
9 // Handle the error
10 });
11
12 return (
13 // JSX code
14 );
15};
In this example, we use axios.get
to make a GET request to the /api/users
endpoint. The response from the server will be passed to the then
method, where we can handle the data and update the component state accordingly.
This way, we can integrate React with Express.js by making HTTP requests from the frontend to the backend API endpoints.
Feel free to explore more about integration techniques and best practices for connecting React with Express.js as you dive deeper into the MERN stack development.
xxxxxxxxxx
`const express = require('express');
const app = express();
app.get('/api/users', (req, res) => {
const users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Smith' }
];
res.json(users);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
`