- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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