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

更新於: 29-Jan-2022

261 次瀏覽

開啟你的 職業生涯

透過完成課程取得認證

開始
廣告
© . All rights reserved.