Menu
CoddyTech

Creare con POST

Fa parte della sezione API REST del percorso Node.js di Coddy. Lezione 2 di 18.

Un client che aggiunge un’attività deve sapere dove si trova la nuova attività. Invia la nuova risorsa all’URL dell’elenco con POST e il server risponde con 201 Created, includendo la risorsa e un’intestazione Location che indica il suo URL.

POST /api/events   { "name": "Launch party" }

201 Created
Location: /api/events/12
{ "id": 12, "name": "Launch party" }

Il server sceglie l’id, quindi due client non possono mai rivendicare lo stesso. Con l’intestazione Location, il client può recuperare il nuovo evento senza dover costruire l’URL da sé. res.location(path) imposta quell’intestazione e si concatena come res.status:

res.status(201).location(`/api/events/${event.id}`).json(event);
challenge icon

Sfida

Facile
  • POST /api/tasks con { "title" } restituisce 201 con la nuova attività: id da nextId() in store.js, done: false, createdAt da new Date().toISOString().
  • Imposta Location su /api/tasks/<id>.
  • Senza title: 400.

Invia { "title": "Order new chairs" }, poi esegui GET sul percorso Location, quindi POST {}.

Provalo tu

import { Router } from 'express';
import { tasks } from '../store.js';

const router = Router();

router.get('/', (req, res) => {
    res.json(tasks);
});

router.get('/:id', (req, res) => {
    const task = tasks.find((t) => t.id === Number(req.params.id));
    if (!task) {
        return res.status(404).json({ error: 'Task not found' });
    }
    res.json(task);
});

export default router;

Tutte le lezioni di API REST