0
0
Expressframework~5 mins

req.method and req.url in Express

Choose your learning style9 modes available
Introduction

We use req.method and req.url to know what kind of request a user made and which page or resource they want. This helps the server decide how to respond.

When you want to check if a user sent a GET or POST request to your server.
When you need to know which page or API endpoint the user is asking for.
When you want to log or track user requests for debugging or analytics.
When you want to handle different actions based on the request type or URL.
Syntax
Express
req.method
req.url

req.method is a string like 'GET', 'POST', 'PUT', etc.

req.url is the path part of the URL, including query strings if any.

Examples
This shows the HTTP method used by the client.
Express
console.log(req.method); // Outputs: 'GET' or 'POST' etc.
This shows the requested URL path and query.
Express
console.log(req.url); // Outputs: '/home' or '/api/data?user=1'
Check if the request is a POST to process form data.
Express
if (req.method === 'POST') {
  // handle form submission
}
Check if the user wants the about page.
Express
if (req.url === '/about') {
  // serve about page
}
Sample Program

This simple Express server replies with the HTTP method and URL the user requested.

Express
import express from 'express';
const app = express();

app.use((req, res) => {
  res.send(`You made a ${req.method} request to ${req.url}`);
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

req.method is always uppercase like 'GET', 'POST'.

req.url includes the path and query string but not the domain.

Use these properties inside middleware or route handlers to customize responses.

Summary

req.method tells you the HTTP method used by the client.

req.url tells you the path and query the client requested.

They help your server understand and respond correctly to user requests.