- 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.acceptsLanguage() Method
The req.acceptsLanguage() method returns the first accepted language out of the specified languages based on the request's Accept-Language HTTP header field. This method returns 'false' if none of the specified language is accepted.
Syntax
req.acceptsLanguage ( lang, [...] )
Example 1
Create a file with the name "reqLang.js" and copy the following code snippet. After creating the file, use the command "node reqLang.js" to run this code as shown in the example below −
// req.acceptsLanguage(lang, [...]) Method Demo Example // Importing the express module 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.acceptsLanguages('en-IN')); console.log(req.get('accept-language')); res.end(); }); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT); });
Hit the Endpoint "localhost:3000/api" with a GET request and set the following property in the header: Accept-Language = en-IN
Output
C:\home
ode>> node reqLang.js Server listening on PORT 3000 en-IN en-IN
Example 2
Let's take a look at one more example.
// req.acceptsLanguage(lang, [...]) Method Demo Example // Importing the express module 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("Is Language of Accepted type: ", req.acceptsLanguages('en-IN', 'en-US')); console.log("Language passed -- ", req.get('accept-language')); 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/api" with a GET Request and set the following property in the headers: Accept-Language = fr-CH
C:\home
ode>> node reqLang.js Server listening on PORT 3000 Is Language of Accepted type: false Language passed -- fr-CH
Advertisements