0
0
ExpressHow-ToBeginner · 3 min read

How to Get Request Method in Express: Simple Guide

In Express, you can get the HTTP request method by accessing the req.method property inside your route handler. This property returns a string like GET, POST, PUT, etc., representing the method used by the client.
📐

Syntax

The req.method property is a string that holds the HTTP method of the incoming request. You use it inside a route handler function where req is the request object.

  • req: The request object provided by Express.
  • method: A string representing the HTTP method (e.g., GET, POST).
javascript
app.get('/example', (req, res) => {
  const method = req.method;
  res.send(`Request method is: ${method}`);
});
💻

Example

This example shows a simple Express server that responds with the HTTP method used in the request. It works for any HTTP method sent to the /check-method route.

javascript
import express from 'express';
const app = express();
const port = 3000;

app.all('/check-method', (req, res) => {
  const method = req.method;
  res.send(`You used the ${method} method.`);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Output
Server running on http://localhost:3000 When you visit http://localhost:3000/check-method with a GET request, the response is: You used the GET method.
⚠️

Common Pitfalls

One common mistake is trying to get the method outside the route handler where req is not available. Another is confusing req.method with other properties like req.url or req.body.

Also, remember that req.method is always uppercase, so comparisons should be case-sensitive or normalized.

javascript
/* Wrong way: Trying to access req.method outside a route handler */
// const method = req.method; // req is undefined here

/* Right way: Inside route handler */
app.post('/submit', (req, res) => {
  if (req.method === 'POST') {
    res.send('This is a POST request');
  } else {
    res.send('Not a POST request');
  }
});
📊

Quick Reference

Here is a quick summary of how to use req.method in Express:

PropertyDescriptionExample Value
req.methodHTTP method of the requestGET, POST, PUT, DELETE
Usage locationInside route handler functionsapp.get('/', (req, res) => {...})
CaseAlways uppercase stringGET
Common useTo check or respond based on methodif (req.method === 'POST') {...}

Key Takeaways

Use req.method inside Express route handlers to get the HTTP method as an uppercase string.
req.method returns values like GET, POST, PUT, DELETE depending on the client request.
Always access req.method inside the route handler where req is defined.
Compare req.method with uppercase strings to avoid case mismatch errors.
Use app.all() to handle all HTTP methods on a route if needed.