Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
res.vary() Method in Express.js
The res.vary() method can be used for adding the field to the Vary response header, if the field does not already exist there. The vary header is basically used for content negotiation.
Syntax
res.vary( field )
Example 1
Create a file with the name "resVary.js" and copy the following code snippet. After creating the file, use the command "node resVary.js" to run this code as shown in the example below −
// res.vary() 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){
res.vary('User-Agent').end();
console.log("User-Agent field added to the Vary header.");
});
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/api
Output
C:\home\node>> node resVary.js Server listening on PORT 3000 User-Agent field added to the Vary header.
Example 2
Let's take a look at one more example.
// res.vary() 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.use('/api', function(req, res, next){
// Adding the header and then calling the middleware
res.vary('User-Agent').send("User-Agent field added to the Vary header.");
// Calling the middleware's next API
next();
})
app.get('/api', function(req, res){
console.log('Headers Modified');
});
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/api
Output
C:\home\node>> node resVary.js Server listening on PORT 3000 Headers Modified
Advertisements
