Skip to content

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.

While there are many HTTP methods, these are the most common ones used when building RESTful APIs:

MethodActionDescription
GETRetrieveRequests a representation of the specified resource. GET requests should be safe and idempotent, meaning they only retrieve data and have no side effects.
POSTCreateSubmits an entity to the specified resource, often causing a change in state or the creation of a new resource on the server.
PUTUpdate/ReplaceReplaces the entire target resource with the request payload. If the resource does not exist, it may be created.
PATCHPartial UpdateApplies partial modifications to a resource. This is preferred over PUT when you only need to update a few fields of an object.
DELETEDeleteDeletes the specified resource.

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 (/).

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 data
app.get('/', (req, res) => {
res.status(200).json({ message: 'GET request received. Welcome to the API!' });
});
// POST: Create data
app.post('/', (req, res) => {
console.log('Request body:', req.body);
res.status(201).json({ message: 'POST request received.', data: req.body });
});
// PUT: Replace data
app.put('/', (req, res) => {
res.status(200).json({ message: 'PUT request received. Resource updated.' });
});
// PATCH: Partially update data
app.patch('/', (req, res) => {
res.status(200).json({ message: 'PATCH request received. Resource partially updated.' });
});
// DELETE: Remove data
app.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}`);
});

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 Created status 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.
  • Forgetting express.json(): If you try to access req.body on a POST or PUT request without using the app.use(express.json()) middleware, req.body will be undefined. 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.