
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
Express.js req.accepts() Method
The req.accepts() method checks if the specified content-types are acceptable by the request's Accept HTTP header fields. This method returns the best match, and returns False if none of the specified content types is acceptable.
The type values can be a MIME type like application/json, or an extension name like json.
Syntax
req.accepts( types )
Example 1
Create a file with the name "reqAccepts.js" and copy the following code snippet. After creating the file, use the command "node reqAccepts.js" to run this code as shown in the example below −
// req.accepts() 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 with req.accepts() fn app.get('/', function (req, res) { console.log(req.get('Accept')); console.log(req.accepts('application/json')); res.end(); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the Endpoint localhost:3000/ with a GET request and set the content-type as 'application/json' and Accept as 'application/json'
C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 application/json application/json
Example 2
Let's take a look at one more example.
// req.accepts() 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 with req.accepts() fn app.get('/', function (req, res) { console.log(req.get('Accept')); console.log(req.accepts('text/html')); res.end(); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Output
Hit the Endpoint localhost:3000/ with a GET request and set the content-type as 'text/plain' and Accept as 'text/plain'
C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 text/plain false