Express.js – req.is() Method


The req.is() method is used for returning the matching content-type. It returns the matching content-type when the incoming request's "Content-type" HTTP header matches with those of the MIME type specified by the type parameter. If the request has no body, then it returns NULL, else it returns False.

Syntax

req.is( type )

The type parameter takes the input for the Content-type to be matched. For example, html, text/html, text/*, etc.

Example 1

Create a file with the name "req.js" and copy the following code snippet. After creating the file, use the command "node req.js" to run this code as shown in the example below −

// req.is() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint
app.get('/', function (req, res) {
   console.log(req.is('application/json'));
   res.end();
});

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 −

http://localhost:3000/

and set the content-type as 'application/json' and also do not leave the request body as empty because an empty request body will return 'NULL' as the response.

Output

C:\home
ode>> node req.js Server listening on PORT 3000 application/json

Example 2

Let's take a look at one more example.

// req.is() Method Demo Example

// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint
app.get('/', function (req, res) {
   console.log(req.is('text/*'));
   res.end();
});

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 −

http://localhost:3000/

and set the content-type anything other than 'text/*' and also do not leave the request body empty because an empty request body will return 'null' as response.

Output

C:\home
ode>> node req.js Server listening on PORT 3000 false

Updated on: 28-Mar-2022

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements