0
0
Node.jsframework~5 mins

HTTP methods and CRUD mapping in Node.js

Choose your learning style9 modes available
Introduction

HTTP methods tell a server what action to perform. CRUD mapping helps connect these actions to common database tasks.

When building a web API to manage data like users or products.
When you want to create, read, update, or delete information on a server.
When designing routes in a Node.js backend using frameworks like Express.
When you want to follow standard web practices for data handling.
When you need clear communication between client and server about data actions.
Syntax
Node.js
GET /resource  // Read data
POST /resource  // Create new data
PUT /resource/:id  // Update existing data fully
PATCH /resource/:id  // Update existing data partially
DELETE /resource/:id  // Delete data

Use GET to get or read data without changing it.

POST adds new data, PUT replaces data, and PATCH changes part of data.

Examples
Gets a list of all users.
Node.js
GET /users
Adds a new user to the database.
Node.js
POST /users
Replaces the user with ID 123 with new data.
Node.js
PUT /users/123
Deletes the user with ID 123.
Node.js
DELETE /users/123
Sample Program

This Node.js Express app shows how HTTP methods map to CRUD actions on a simple user list.

GET reads users, POST adds a user, PUT updates a user fully, and DELETE removes a user.

Node.js
import express from 'express';
const app = express();
app.use(express.json());

let users = [{ id: 1, name: 'Alice' }];

// Read all users
app.get('/users', (req, res) => {
  res.json(users);
});

// Create a new user
app.post('/users', (req, res) => {
  const newUser = { id: Date.now(), name: req.body.name };
  users.push(newUser);
  res.status(201).json(newUser);
});

// Update a user fully
app.put('/users/:id', (req, res) => {
  const id = Number(req.params.id);
  const index = users.findIndex(u => u.id === id);
  if (index === -1) return res.status(404).send('User not found');
  users[index] = { id, name: req.body.name };
  res.json(users[index]);
});

// Delete a user
app.delete('/users/:id', (req, res) => {
  const id = Number(req.params.id);
  users = users.filter(u => u.id !== id);
  res.status(204).send();
});

app.listen(3000, () => console.log('Server running on port 3000'));
OutputSuccess
Important Notes

Always use express.json() middleware to parse JSON request bodies.

Use status codes like 201 for created and 204 for no content to communicate results clearly.

PUT replaces the whole resource; PATCH (not shown) updates parts of it.

Summary

HTTP methods map to CRUD: GET=Read, POST=Create, PUT=Update, DELETE=Delete.

Use these methods to build clear and standard web APIs.

Express makes it easy to connect HTTP methods to code actions.