Applicativo Client Server REACT-NODE-Express

Ben ritrovato. Ecco la parte teorica del tuo nuovo progettino che ti aprirà una nuova visione sulle mobile app client-serve con l’utilizzo dell’API.

Welcome back. Here's the theoretical part of your new project that will open up a new vision for you on client-server mobile apps using APIs. In this article, I'll explain how you can connect your React front-end created with Vite to your Node.js or Express back-end. Without further ado, let's get started. First, I opened VS Code in a directory called vite-express-video, where I opened the terminal and we'll start by creating our React front-end. Then I'll guide you through the configuration of the back-end. Create the vite-express-video directory and with the terminal prompt you can use the command code . in the directory and it will open directly in VS Code. Then, we can start with npm create vite@latest (or npm create vite) and we'll be asked a series of questions about our app. First, we need to install the create-vite package, so I press enter. For information on this, I can refer you to the https://vite.dev/guide/ website in the scaffolding section. It will ask for the project name, and for this, I simply write client. Then it will ask us to select a framework: as you can guess from the title of the video, we'll select React. At the variant option, I select JavaScript. Now that the project has been created, we enter the client directory with cd client and then run npm install to install all the necessary dependencies. After a few seconds, once all the dependencies have been installed, we can proceed to configure the back-end. PART SERVER Therefore, once the front-end is created, I'll show you how to create the server. I create a server directory by going to the Explorer section and clicking on the "create folder" icon. Then, I clear the terminal and enter the server directory with cd .. to exit the client directory, and then cd server to enter the server directory. Here, I run npm init -y to generate a package.json file with the default settings. If you expand the server folder, you'll see that the file has been created. Now, we open package.json to configure it. We change the server entry point from index.js (default value) to server.js. This is just a personal preference: if you want, you can leave index.js or use a different name. So, I create the file with touch server.js, which now appears in the project. Now, we install the necessary dependencies for the back-end. First, I clear the terminal and install Express with npm i express. Then, we install nodemon with npm i nodemon -D so that the server restarts automatically when we modify the code. After installation, we update the scripts in package.json. We add:

"start": "node server",
"dev": "nodemon server"

Make sure that after node or nodemon there is the correct name of your startup file (in this case, server.js). Now, we can start creating our back-end API. We open server.js and write:

const express = require('express');
const app = express();

app.get('/api', (req, res) => {
res.json({ fruits: ['apple', 'orange', 'banana'] });
});

app.listen(8080, () => {
console.log('Server started on port 8080');
});

The server listens on port 8080. If you go to http://localhost:8080/api in your browser, you'll see an object with an array called fruits. Now, we need to configure CORS so that the back-end accepts requests from the front-end. We open a new terminal in the server folder and run npm i cors. Then, in the code, we import and configure CORS:

const cors = require('cors');
const corsOptions = { origin: 'http://localhost:5173' };
app.use(cors(corsOptions));

Perfect. Now, we can move on to the front-end. We enter the client directory with cd ../client, clear the terminal, and install Axios with npm i axios. We open src/App.jsx, start the front-end server with npm run dev, and visit http://localhost:5173. To test data fetching, we do the following:

import { useEffect, useState } from 'react';
import axios from 'axios';

function App() {
const [array, setArray] = useState([]);

useEffect(() => {
const fetchApi = async () => {
const response = await axios.get('http://localhost:8080/api');
console.log(response.data.fruits);
setArray(response.data.fruits);
};
fetchApi();
}, []);

return (

{array.map((fruit, index) => (

{fruit}

))}

);
}

export default App;

Now, if you update the page, you'll see apple, orange, and banana displayed. If you change the data in the back-end (for example, from orange to strawberry), saving and updating the front-end, you'll see the change applied automatically, thanks to nodemon.

Summary: