Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
req.method Property in Express.js
The req.method property contains a string that corresponds to the HTTP methods of the request which are GET, POST, PUT, DELETE, and so on...
These methods are based upon the requests sent by the user. All the above methods have different use-cases.
Syntax
req.method
Example 1
Create a file with the name "reqMethod.js" and copy the following code snippet. After creating the file, use the command "node reqMethod.js" to run this code as shown in the example below −
// req.method Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining an Endpoint
app.get('/api', function (req, res) {
console.log(req.method);
res.send(req.method);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint with a GET request − localhost:3000/api
Output
C:\home
ode>> node reqMethod.js Server listening on PORT 3000 GET
Example 2
Let's take a look at one more example.
// req.method Property Demo Example
// Importing the express & cookieParser module
var cookieParser = require('cookie-parser');
var express = require('express');
// Initializing the express and port number
var app = express();
// Initializing the router from express
var router = express.Router();
var PORT = 3000;
// Defining multiple Endpoint
app.get('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.post('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.put('/api', function (req, res) {
console.log("Request Method is: ", req.method);
res.send(req.method);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
Hit the following Endpoint one by one −
GET Request −localhost:3000/api
POST Request −localhost:3000/api
PUT Request −localhost:3000/api
Output
C:\home
ode>> node reqMethod.js Server listening on PORT 3000 Request Method is: GET Request Method is: POST Request Method is: PUT
Advertisements