0
0
Expressframework~5 mins

HTTP methods for CRUD operations in Express

Choose your learning style9 modes available
Introduction

HTTP methods help your server know what action to do with data. They match common tasks like creating, reading, updating, or deleting information.

When you want to add new data to a database.
When you need to get or show data to users.
When you want to change existing data.
When you want to remove data from storage.
When building a REST API to handle data operations.
Syntax
Express
app.METHOD(PATH, HANDLER)

// METHOD can be GET, POST, PUT, DELETE, PATCH
// PATH is the URL path
// HANDLER is a function to run when the route is called

Use GET to read data without changing it.

Use POST to create new data.

Examples
This handles reading all items.
Express
app.get('/items', (req, res) => {
  res.send('Get all items')
})
This handles adding a new item.
Express
app.post('/items', (req, res) => {
  res.send('Create a new item')
})
This updates an existing item fully.
Express
app.put('/items/:id', (req, res) => {
  res.send(`Update item with id ${req.params.id}`)
})
This deletes an item by id.
Express
app.delete('/items/:id', (req, res) => {
  res.send(`Delete item with id ${req.params.id}`)
})
Sample Program

This Express app shows how to use HTTP methods for CRUD on notes. Each route matches a CRUD action.

Express
import express from 'express'
const app = express()
app.use(express.json())

// Create (POST)
app.post('/notes', (req, res) => {
  res.send('Note created')
})

// Read (GET)
app.get('/notes', (req, res) => {
  res.send('List of notes')
})

// Update (PUT)
app.put('/notes/:id', (req, res) => {
  res.send(`Note ${req.params.id} updated`)
})

// Delete (DELETE)
app.delete('/notes/:id', (req, res) => {
  res.send(`Note ${req.params.id} deleted`)
})

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000')
})
OutputSuccess
Important Notes

Use PATCH if you want to update only part of data, not the whole.

Always test your routes with tools like Postman or browser to see if they work.

Summary

GET reads data.

POST creates data.

PUT updates data fully.

DELETE removes data.