Introduction
HTTP methods help your server know what action to do with data. They match common tasks like creating, reading, updating, or deleting information.
Jump into concepts and practice - no test required
HTTP methods help your server know what action to do with data. They match common tasks like creating, reading, updating, or deleting information.
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.
app.get('/items', (req, res) => { res.send('Get all items') })
app.post('/items', (req, res) => { res.send('Create a new item') })
app.put('/items/:id', (req, res) => { res.send(`Update item with id ${req.params.id}`) })
app.delete('/items/:id', (req, res) => { res.send(`Delete item with id ${req.params.id}`) })
This Express app shows how to use HTTP methods for CRUD on notes. Each route matches a CRUD action.
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') })
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.
GET reads data.
POST creates data.
PUT updates data fully.
DELETE removes data.
/users?PUT /items/5?
app.put('/items/:id', (req, res) => {
res.status(200).send(`Updated item ${req.params.id}`);
});app.delete('/users/:id', (req, res) => {
const userId = req.params;
deleteUser(userId);
res.send('User deleted');
});