Questo tutorial ti insegna come creare un'app CRUD di base utilizzando React per il frontend ed Express per il backend con un database MySQL.
Lukas
Created: June 17, 2025
Updated: July 1, 2025
In questo tutorial completo, imparerai a creare un'applicazione CRUD (Create, Read, Update, Delete) full-stack utilizzando React per il front-end e Node.js con Express per il back-end, il tutto supportato da un database MySQL. Utilizzeremo tecnologie come React Router, Axios e TailwindCSS per migliorare l'esperienza utente.
Svilupperemo un'applicazione full-stack in cui gli utenti possono gestire dei tutorial. Ogni tutorial avrà i seguenti attributi:
Gli utenti possono eseguire le seguenti azioni:
Di seguito, troverai alcuni screenshot di esempio:
L'applicazione segue un'architettura client-server:
Crea la directory del progetto:
mkdir react-node-express-mysql-crud cd react-node-express-mysql-crud
Inizializza l'app Node.js:
npm init -y
Installa le dipendenze:
npm install express sequelize mysql2 cors --save
Usa la sintassi ESModule Aggiungi la seguente riga al tuo file package.json:
{ "type": "module" // ... }
app/config/db.config.js
):export default { HOST: "localhost", USER: "root", PASSWORD: "root", DB: "db", PORT: 8081, dialect: "mysql", pool: { max: 5, min: 0, acquire: 30000, idle: 10000, }, };
app/models/index.js
):import dbConfig from "../config/db.config.js"; import Sequelize from "sequelize"; import Tutorial from "./tutorial.model.js"; const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, { host: dbConfig.HOST, dialect: dbConfig.dialect, pool: dbConfig.pool, port: dbConfig.PORT, }); const db = {}; db.Sequelize = Sequelize; db.sequelize = sequelize; db.tutorials = Tutorial(sequelize, Sequelize); export default db;
app/models/tutorial.model.js
):export default (sequelize, Sequelize) => { const Tutorial = sequelize.define("tutorial", { title: { type: Sequelize.STRING, }, description: { type: Sequelize.STRING, }, published: { type: Sequelize.BOOLEAN, }, }); return Tutorial; };
Se non hai un database MySQL per lo sviluppo locale, puoi usare Docker per creare un container MySQL temporaneo:
docker run --rm -p 3306:3306 \ -e MYSQL_ROOT_PASSWORD=root \ -e MYSQL_DATABASE=db \ mysql:8
app/controllers/tutorial.controller.js
):import db from "../models/index.js"; const Op = db.Sequelize.Op; const Tutorial = db.tutorials; // Crea e salva un nuovo Tutorial export const create = (req, res) => { // Valida la richiesta if (!req.body.title) { res.status(400).send({ message: "Il contenuto non può essere vuoto!", }); return; } // Crea un Tutorial const tutorial = { title: req.body.title, description: req.body.description, published: req.body.published ? req.body.published : false, }; // Salva il Tutorial nel database Tutorial.create(tutorial) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Si è verificato un errore durante la creazione del Tutorial.", }); }); }; // Recupera tutti i Tutorial export const findAll = (req, res) => { // Consenti una condizione di filtro tramite parametro di query const title = req.query.title; const condition = title ? { title: { [Op.like]: `%${title}%` } } : null; Tutorial.findAll({ where: condition }) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Si è verificato un errore durante il recupero dei tutorial.", }); }); }; // Trova un singolo Tutorial tramite ID export const findOne = (req, res) => { const id = req.params.id; // Trova il Tutorial tramite chiave primaria Tutorial.findByPk(id) .then((data) => { if (data) { res.send(data); } else { res.status(404).send({ message: `Impossibile trovare il Tutorial con id=${id}.`, }); } }) .catch((err) => { res.status(500).send({ message: "Errore nel recupero del Tutorial con id=" + id, }); }); }; // Aggiorna un Tutorial tramite ID export const update = (req, res) => { const id = req.params.id; // Aggiorna il Tutorial con l'ID specificato Tutorial.update(req.body, { where: { id: id }, }) .then((num) => { if (num == 1) { res.send({ message: "Tutorial aggiornato con successo.", }); } else { res.send({ message: `Impossibile aggiornare il Tutorial con id=${id}. Forse il Tutorial non è stato trovato o req.body è vuoto!`, }); } }) .catch((err) => { res.status(500).send({ message: "Errore nell'aggiornamento del Tutorial con id=" + id, }); }); }; // Elimina un Tutorial tramite ID export const deleteOne = (req, res) => { const id = req.params.id; // Elimina il Tutorial con l'ID specificato Tutorial.destroy({ where: { id: id }, }) .then((num) => { if (num == 1) { res.send({ message: "Tutorial eliminato con successo!", }); } else { res.send({ message: `Impossibile eliminare il Tutorial con id=${id}. Forse il Tutorial non è stato trovato!`, }); } }) .catch((err) => { res.status(500).send({ message: "Impossibile eliminare il Tutorial con id=" + id, }); }); }; // Elimina tutti i Tutorial export const deleteAll = (req, res) => { // Elimina tutti i Tutorial Tutorial.destroy({ where: {}, truncate: false, }) .then((nums) => { res.send({ message: `${nums} Tutorial sono stati eliminati con successo!` }); }) .catch((err) => { res.status(500).send({ message: err.message || "Si è verificato un errore durante la rimozione di tutti i tutorial.", }); }); }; // Trova tutti i Tutorial pubblicati export const findAllPublished = (req, res) => { // Trova tutti i Tutorial con published = true Tutorial.findAll({ where: { published: true } }) .then((data) => { res.send(data); }) .catch((err) => { res.status(500).send({ message: err.message || "Si è verificato un errore durante il recupero dei tutorial.", }); }); };
app/routes/tutorial.routes.js
):import * as tutorials from "../controllers/tutorial.controller.js"; import express from "express"; export default (app) => { let router = express.Router(); // Crea un nuovo Tutorial router.post("/", tutorials.create); // Recupera tutti i Tutorial router.get("/", tutorials.findAll); // Recupera un singolo Tutorial con id router.get("/:id", tutorials.findOne); // Aggiorna un Tutorial con id router.put("/:id", tutorials.update); // Elimina un Tutorial con id router.delete("/:id", tutorials.deleteOne); // Elimina tutti i Tutorial router.delete("/", tutorials.deleteAll); // Trova tutti i Tutorial pubblicati router.get("/published", tutorials.findAllPublished); app.use("/api/tutorials", router); };
server.js
):import express from "express"; import cors from "cors"; import db from "./app/models/index.js"; import tutorialRoutes from "./app/routes/tutorial.routes.js"; const app = express(); const corsOptions = { origin: "http://localhost:5173", }; app.use(cors(corsOptions)); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Route semplice app.get("/", (req, res) => { res.json({ message: "Benvenuto nell'applicazione Tutorial." }); }); // Route tutorialRoutes(app); // Sincronizza database db.sequelize.sync().then(() => { console.log("Database sincornizzato."); }); const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`Server in esecuzione sulla porta ${PORT}.`); });
node server.js
Output:
Server in esecuzione sulla porta 8080. Database sincornizzato.
Questa è l'architettura:
In alternativa, puoi usare Redux:
La struttura finale dei tuoi file sarà simile a questa:
frontend/ ├─ index.html ├─ package.json ├─ postcss.config.js ├─ tailwind.config.js ├─ vite.config.js ├─ src/ │ ├─ App.jsx │ ├─ main.jsx │ ├─ index.css │ ├─ services/ │ │ └─ tutorial.service.js │ └─ pages/ │ ├─ AddTutorial.jsx │ ├─ Tutorial.jsx │ └─ TutorialsList.jsx
Esegui i seguenti comandi per configurare una nuova app React utilizzando Vite:
npm create vite@latest frontend -- --template react cd frontend npm i npm i react-router-dom axios npm install -D tailwindcss autoprefixer npx tailwindcss init -p
Infine, imposta l'opzione content
di Tailwind nel file di configurazione
tailwind.config.js
:
/** @type {import('tailwindcss').Config} */ export default { content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], theme: { extend: {}, }, plugins: [], };
Quindi, apri src/index.css (Vite ha creato questo file per te) e aggiungi le direttive di Tailwind:
@tailwind base; @tailwind components; @tailwind utilities;
Il componente App.jsx
configura le route di React Router e imposta una navbar di base
con Tailwind. Navigheremo tra:
/tutorials
– elenco dei tutorial/add
– modulo per creare un nuovo tutorial/tutorials/:id
– modifica di un singolo tutorialimport { BrowserRouter, Routes, Route, Link } from "react-router-dom"; import TutorialsList from "./pages/TutorialsList"; import AddTutorial from "./pages/AddTutorial"; import Tutorial from "./pages/Tutorial"; function App() { return ( <BrowserRouter> <div> {/* NAVBAR */} <nav className="bg-blue-600 p-4 text-white"> <div className="flex space-x-4"> <Link to="/tutorials" className="hover:text-gray-300 font-bold"> Tutorials </Link> <Link to="/add" className="hover:text-gray-300"> Add </Link> </div> </nav> {/* ROUTE */} <div className="container mx-auto mt-8 px-4"> <Routes> <Route path="/" element={<TutorialsList />} /> <Route path="/tutorials" element={<TutorialsList />} /> <Route path="/add" element={<AddTutorial />} /> <Route path="/tutorials/:id" element={<Tutorial />} /> </Routes> </div> </div> </BrowserRouter> ); } export default App;
Questo servizio gestisce le richieste HTTP di Axios verso il nostro backend Node/Express (http://localhost:8080/api). Aggiorna la baseURL se il tuo server è in esecuzione su un indirizzo o una porta diversi.
import axios from "axios"; const http = axios.create({ baseURL: "http://localhost:8080/api", headers: { "Content-Type": "application/json", }, }); const getAll = () => { return http.get("/tutorials"); }; const get = (id) => { return http.get(`/tutorials/${id}`); }; const create = (data) => { return http.post("/tutorials", data); }; const update = (id, data) => { return http.put(`/tutorials/${id}`, data); }; const remove = (id) => { return http.delete(`/tutorials/${id}`); }; const removeAll = () => { return http.delete("/tutorials"); }; const findByTitle = (title) => { return http.get(`/tutorials?title=${title}`); }; export default { getAll, get, create, update, remove, removeAll, findByTitle, };
Un componente per creare nuovi tutorial in src/pages/AddTutorial.jsx
. Permette di
inserire titolo e descrizione, e poi chiama TutorialService.create()
.
import React, { useState } from "react"; import TutorialService from "../services/tutorial.service"; function AddTutorial() { const [title, setTitle] = useState(""); const [description, setDescription] = useState(""); const [submitted, setSubmitted] = useState(false); const saveTutorial = () => { const data = { title, description }; TutorialService.create(data) .then((response) => { console.log(response.data); setSubmitted(true); }) .catch((e) => { console.log(e); }); }; const newTutorial = () => { setTitle(""); setDescription(""); setSubmitted(false); }; return ( <div className="max-w-sm mx-auto p-4 bg-white rounded shadow"> {submitted ? ( <div> <h4 className="font-bold text-green-600 mb-4"> Tutorial inviato con successo! </h4> <button className="bg-blue-500 text-white px-3 py-1 rounded" onClick={newTutorial} > Aggiungine un altro </button> </div> ) : ( <div> <h4 className="font-bold text-xl mb-2">Aggiungi Tutorial</h4> <div className="mb-2"> <label className="block mb-1 font-medium">Titolo</label> <input type="text" className="border border-gray-300 rounded w-full px-2 py-1" value={title} onChange={(e) => setTitle(e.target.value)} /> </div> <div className="mb-2"> <label className="block mb-1 font-medium">Descrizione</label> <input type="text" className="border border-gray-300 rounded w-full px-2 py-1" value={description} onChange={(e) => setDescription(e.target.value)} /> </div> <button className="bg-green-500 text-white px-3 py-1 rounded mt-2" onClick={saveTutorial} > Invia </button> </div> )} </div> ); } export default AddTutorial;
Un componente in src/pages/TutorialsList.jsx
che:
import { useState, useEffect } from "react"; import TutorialService from "../services/tutorial.service"; import { Link } from "react-router-dom"; function TutorialsList() { const [tutorials, setTutorials] = useState([]); const [currentTutorial, setCurrentTutorial] = useState(null); const [currentIndex, setCurrentIndex] = useState(-1); const [searchTitle, setSearchTitle] = useState(""); useEffect(() => { retrieveTutorials(); }, []); const onChangeSearchTitle = (e) => { setSearchTitle(e.target.value); }; const retrieveTutorials = () => { TutorialService.getAll() .then((response) => { setTutorials(response.data); console.log(response.data); }) .catch((e) => { console.log(e); }); }; const refreshList = () => { retrieveTutorials(); setCurrentTutorial(null); setCurrentIndex(-1); }; const setActiveTutorial = (tutorial, index) => { setCurrentTutorial(tutorial); setCurrentIndex(index); }; const removeAllTutorials = () => { TutorialService.removeAll() .then((response) => { console.log(response.data); refreshList(); }) .catch((e) => { console.log(e); }); }; const findByTitle = () => { TutorialService.findByTitle(searchTitle) .then((response) => { setTutorials(response.data); setCurrentTutorial(null); setCurrentIndex(-1); console.log(response.data); }) .catch((e) => { console.log(e); }); }; return ( <div className="flex flex-col lg:flex-row gap-8"> {/* COLONNA SINISTRA: RICERCA + ELENCO */} <div className="flex-1"> <div className="flex mb-4"> <input type="text" className="border border-gray-300 rounded-l px-2 py-1 w-full" placeholder="Cerca per titolo" value={searchTitle} onChange={onChangeSearchTitle} /> <button className="bg-blue-500 text-white px-4 py-1 rounded-r" onClick={findByTitle} > Cerca </button> </div> <h4 className="font-bold text-lg mb-2">Elenco Tutorial</h4> <ul className="divide-y divide-gray-200 border border-gray-200 rounded"> {tutorials && tutorials.map((tutorial, index) => ( <li className={ "px-4 py-2 cursor-pointer " + (index === currentIndex ? "bg-blue-100" : "") } onClick={() => setActiveTutorial(tutorial, index)} key={index} > {tutorial.title} </li> ))} </ul> <button className="bg-red-500 text-white px-3 py-1 rounded mt-4" onClick={removeAllTutorials} > Rimuovi tutto </button> </div> {/* COLONNA DESTRA: DETTAGLI */} <div className="flex-1"> {currentTutorial ? ( <div className="p-4 bg-white rounded shadow"> <h4 className="font-bold text-xl mb-2">Tutorial</h4> <div className="mb-2"> <strong>Titolo: </strong> {currentTutorial.title} </div> <div className="mb-2"> <strong>Descrizione: </strong> {currentTutorial.description} </div> <div className="mb-2"> <strong>Stato: </strong> {currentTutorial.published ? "Pubblicato" : "In attesa"} </div> <Link to={`/tutorials/${currentTutorial.id}`} className="inline-block bg-yellow-400 text-black px-3 py-1 rounded" > Modifica </Link> </div> ) : ( <div> <p>Per favore, clicca su un Tutorial...</p> </div> )} </div> </div> ); } export default TutorialsList;
Un componente funzionale in src/pages/Tutorial.jsx
per visualizzare e modificare un
singolo tutorial. Utilizza:
useParams()
per ottenere :id
dall'URLuseNavigate()
per reindirizzareTutorialService
per le operazioni di get, update e deleteimport { useState, useEffect } from "react"; import { useParams, useNavigate } from "react-router-dom"; import TutorialService from "../services/tutorial.service"; function Tutorial() { const { id } = useParams(); const navigate = useNavigate(); const [currentTutorial, setCurrentTutorial] = useState({ id: null, title: "", description: "", published: false, }); const [message, setMessage] = useState(""); const getTutorial = (id) => { TutorialService.get(id) .then((response) => { setCurrentTutorial(response.data); console.log(response.data); }) .catch((e) => { console.log(e); }); }; useEffect(() => { if (id) getTutorial(id); }, [id]); const handleInputChange = (event) => { const { name, value } = event.target; setCurrentTutorial({ ...currentTutorial, [name]: value }); }; const updatePublished = (status) => { const data = { ...currentTutorial, published: status, }; TutorialService.update(currentTutorial.id, data) .then((response) => { setCurrentTutorial({ ...currentTutorial, published: status }); console.log(response.data); }) .catch((e) => { console.log(e); }); }; const updateTutorial = () => { TutorialService.update(currentTutorial.id, currentTutorial) .then((response) => { console.log(response.data); setMessage("Il tutorial è stato aggiornato con successo!"); }) .catch((e) => { console.log(e); }); }; const deleteTutorial = () => { TutorialService.remove(currentTutorial.id) .then((response) => { console.log(response.data); navigate("/tutorials"); }) .catch((e) => { console.log(e); }); }; return ( <div> {currentTutorial ? ( <div className="max-w-sm mx-auto p-4 bg-white rounded shadow"> <h4 className="font-bold text-xl mb-2">Modifica Tutorial</h4> <div className="mb-2"> <label className="block font-medium" htmlFor="title"> Titolo </label> <input type="text" className="border border-gray-300 rounded w-full px-2 py-1" id="title" name="title" value={currentTutorial.title} onChange={handleInputChange} /> </div> <div className="mb-2"> <label className="block font-medium" htmlFor="description"> Descrizione </label> <input type="text" className="border border-gray-300 rounded w-full px-2 py-1" id="description" name="description" value={currentTutorial.description} onChange={handleInputChange} /> </div> <div className="mb-2"> <strong>Stato:</strong>{" "} {currentTutorial.published ? "Pubblicato" : "In attesa"} </div> <div className="space-x-2 mt-2"> {currentTutorial.published ? ( <button className="bg-blue-500 text-white px-3 py-1 rounded" onClick={() => updatePublished(false)} > Rimuovi pubblicazione </button> ) : ( <button className="bg-blue-500 text-white px-3 py-1 rounded" onClick={() => updatePublished(true)} > Pubblica </button> )} <button className="bg-red-500 text-white px-3 py-1 rounded" onClick={deleteTutorial} > Elimina </button> <button className="bg-green-500 text-white px-3 py-1 rounded" onClick={updateTutorial} > Aggiorna </button> </div> {message && <p className="text-green-600 mt-2">{message}</p>} </div> ) : ( <div> <p>Caricamento tutorial in corso...</p> </div> )} </div> ); } export default Tutorial;
npm run dev
Ora puoi accedere all'applicazione all'indirizzo http://localhost:5173. Apri quell'URL nel tuo browser. Ora puoi navigare su:
/tutorials
– vedi tutti i tutorial/add
– aggiungi un tutorial/tutorials/:id
– modifica un tutorial specifico(Assicurati che il tuo back-end Node/Express sia in esecuzione su http://localhost:8080 o aggiorna di conseguenza la baseURL in tutorial.service.js.)
Hai costruito con successo un'applicazione CRUD full-stack utilizzando React, Node.js, Express e MySQL. Questo progetto mostra come impostare un'API RESTful con Node.js ed Express, gestire i dati con l'ORM Sequelize e creare un frontend reattivo con React e Bootstrap.
Buona programmazione e al prossimo tutorial!
Enjoyed this read?
🤝 Join our Passkeys Community
Share passkeys implementation tips and get support to free the world from passwords.
🚀 Subscribe to Substack
Get the latest news, strategies, and insights about passkeys sent straight to your inbox.
Related Articles
Table of Contents