ExpressJS - HTTP Methods
Express.js - Handling HTTP Request Methods
Section titled “Express.js - Handling HTTP Request Methods”In web applications, the HTTP method (or verb) defines the action a client wants to perform on a specific resource. Express provides a clean, declarative way to handle these different methods for each route in your application.
Core HTTP Methods in RESTful APIs
Section titled “Core HTTP Methods in RESTful APIs”While there are many HTTP methods, these are the most common ones used when building RESTful APIs:
| Method | Action | Description |
|---|---|---|
| GET | Retrieve | Requests a representation of the specified resource. GET requests should be safe and idempotent, meaning they only retrieve data and have no side effects. |
| POST | Create | Submits an entity to the specified resource, often causing a change in state or the creation of a new resource on the server. |
| PUT | Update/Replace | Replaces the entire target resource with the request payload. If the resource does not exist, it may be created. |
| PATCH | Partial Update | Applies partial modifications to a resource. This is preferred over PUT when you only need to update a few fields of an object. |
| DELETE | Delete | Deletes the specified resource. |
Implementing Method Handlers in Express
Section titled “Implementing Method Handlers in Express”Express provides direct methods on the app object that correspond to each HTTP verb: app.get(), app.post(), app.put(), app.patch(), and app.delete().
Let’s create an example that defines a handler for each of these common methods on the root path (/).
Code Example: src/index.js
Section titled “Code Example: src/index.js”import express from 'express';
const app = express();const PORT = 3000;
// Middleware to parse JSON bodies. This is a modern replacement for `body-parser`.app.use(express.json());
// GET: Retrieve dataapp.get('/', (req, res) => { res.status(200).json({ message: 'GET request received. Welcome to the API!' });});
// POST: Create dataapp.post('/', (req, res) => { console.log('Request body:', req.body); res.status(201).json({ message: 'POST request received.', data: req.body });});
// PUT: Replace dataapp.put('/', (req, res) => { res.status(200).json({ message: 'PUT request received. Resource updated.' });});
// PATCH: Partially update dataapp.patch('/', (req, res) => { res.status(200).json({ message: 'PATCH request received. Resource partially updated.' });});
// DELETE: Remove dataapp.delete('/', (req, res) => { res.status(200).json({ message: 'DELETE request received. Resource deleted.' });});
app.listen(PORT, () => { console.log(`Server is running at http://localhost:${PORT}`);});Testing Your Endpoints
Section titled “Testing Your Endpoints”After running your server with npm run dev, you need an API client like Postman or Insomnia to test methods other than GET.
- Test GET: Open
http://localhost:3000/in your browser. You’ll see the JSON response for the GET request. - Test POST: In your API client, create a new request.
- Set the method to POST.
- Set the URL to
http://localhost:3000/. - Go to the ‘Body’ tab, select ‘raw’, and choose ‘JSON’ from the dropdown.
- Enter a JSON object like
{ "name": "My New Item" }. - Send the request. You will receive a
201 Createdstatus and a confirmation message.
- Test PUT, PATCH, and DELETE: Follow a similar process for the other methods. Set the method type in your API client and send the request to
http://localhost:3000/. You will see the corresponding message for each.
Common Pitfalls
Section titled “Common Pitfalls”- Forgetting
express.json(): If you try to accessreq.bodyon a POST or PUT request without using theapp.use(express.json())middleware,req.bodywill beundefined. This is a very common mistake for beginners. - Using GET for state-changing actions: A GET request should never modify data on the server. Always use POST, PUT, PATCH, or DELETE for actions that create, update, or delete resources.