Mark As Completed Discussion

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:

  1. 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.

  2. 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  });
  1. 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.

  2. 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});
JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment