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:
| Property | Description | Example Value |
|---|---|---|
| req.method | HTTP method of the request | GET, POST, PUT, DELETE |
| Usage location | Inside route handler functions | app.get('/', (req, res) => {...}) |
| Case | Always uppercase string | GET |
| Common use | To check or respond based on method | if (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.