Sobes.tech
Intern

Cos'è CRUD?

sobes.tech AI

Risposta dell'AI

CRUD è un acronimo che descrive le operazioni principali eseguite sui dati:

  • Create (Creazione): Aggiunta di nuovi dati.
  • Read (Lettura): Ottenimento di dati esistenti.
  • Update (Aggiornamento): Modifica di dati esistenti.
  • Delete (Eliminazione): Cancellazione dei dati.

Nello sviluppo frontend, queste operazioni spesso corrispondono ai metodi HTTP durante l'interazione con il backend tramite API:

Operazione CRUD Metodo HTTP Descrizione
Create POST Inviare dati per creare.
Read GET Richiedere dati.
Update PUT / PATCH Inviare dati per aggiornare.
Delete DELETE Richiedere l'eliminazione dei dati.

Esempio di implementazione nel frontend con JavaScript per interagire con REST API:

// Supponiamo di avere un oggetto user e di volerlo creare sul server
fetch('/api/users', {
  method: 'POST', // Creare
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Nuovo Utente', email: 'nuovo.utente@esempio.com' }),
})
  .then(response => response.json())
  .then(data => console.log('Utente creato:', data))
  .catch(error => console.error('Errore durante la creazione dell’utente:', error));

// Esempio di lettura dati
fetch('/api/users/1') // Per utente con ID 1
  .then(response => response.json())
  .then(data => console.log('Dati utente:', data))
  .catch(error => console.error('Errore nel recupero utente:', error));

// Esempio di aggiornamento dati
fetch('/api/users/1', {
  method: 'PUT', // Aggiornare
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ name: 'Utente Aggiornato' }),
})
  .then(response => response.json())
  .then(data => console.log('Utente aggiornato:', data))
  .catch(error => console.error('Errore nell’aggiornamento utente:', error));

// Esempio di eliminazione dati
fetch('/api/users/1', {
  method: 'DELETE', // Eliminare
})
  .then(response => {
    if (response.ok) {
      console.log('Utente eliminato');
    } else {
      console.error('Errore durante l’eliminazione utente:', response.status);
    }
  })
  .catch(error => console.error('Errore durante l’eliminazione utente:', error));