How to Connect frontend to the backend?

Objectives

What this blog will cover:

In this blog, I’ll walk you through the process of connecting your simple React app to a simple Node/Express API that we will create.

The objective here is to give you a practical guide on how to set up and connect the front-end client and the back-end API.

Step 1: Create a React App

This process is really straightforward.

I will be using create-react-app to easily create a react app named client:

$ npx create-react-app client
$ cd client
$ npm install
$ npm start

The commands above are simple, the first line uses node to create the React application, second moves us into the newly created directory called client which is our app. Finally, we start running the application to run it on our localhost (default localhost:3000).

Step 2: Create a Express App

I will be using the ExpressJS to quickly create an application skeleton and name it exp:

$ mkdir exp
$ cd exp

create a directory to hold your application, and make that your working directory.

$ npm init

This command prompts you for a number of things, such as the name and version of your application. For now, you can simply hit RETURN to accept the defaults for most of them, with the following exception:

$ npm install express --save

Now install Express in the exp directory and save it in the dependencies list.

Step 3: Setting up simple backend server

const express = require('express') 
const app = express() 
const port = 8080 

app.get('/', (req, res) => {   res.send('Hello World!') }) 

app.listen(port, () => {   
console.log(`Example app listening at http://localhost:${port}`) })

After completing step 3 within the integrated terminal we can run node index.js to deploy our backend server locally.

Once you have a simple backend server we can go back to the React application and edit the package.json file. In that file, we need to add “proxy”: http://localhost:8080″

The two applications can now talk to each other. Depending on what you want to do we can specify get and post functions in our backend and link it to our front end using Axios.

Problem when cloning vs code project from GitHub

Problem: After cloning VS Code project I ran into the following error:

Error: No version of chokidar is available. Tried chokidar@2 and chokidar@3. chokidar@2: Error: Cannot find module ‘watchpack-chokidar2

The error would occur when trying to run ‘npm start’, it will compile the code successfully but fail to load the webpage.

Solution: In order to fix this error, I had to delete node_modules folder and the package-lock.json file. Then clear my cache and update my npm globally. Finally running ‘npm install‘ reinstalled the necessary files in order to compile the code correctly. Following these steps eradicated the error.

https://stackoverflow.com/questions/66734503/react-npm-start-not-working-no-version-of-chokidar-available