Express.js 中的 res.vary() 方法
res.vary() 方法可用于将字段添加到 Vary 响应头中(如果该字段尚不存在)。vary 头基本上用于内容协商。
语法
res.vary( field )
例 1
使用名称 "resVary.js" 创建一个文件,并复制以下代码段。创建文件后,使用命令 "node resVary.js" 运行此代码,如下例所示 −
// 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);
});使用 GET 请求访问以下端点 − https://:3000/api
输出
C:\home
ode>> node resVary.js Server listening on PORT 3000 User-Agent field added to the Vary header.
例 2
让我们看一个示例。
// 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);
});使用 GET 请求访问以下端点 − https://:3000/api
输出
C:\home
ode>> node resVary.js Server listening on PORT 3000 Headers Modified
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP