Express.js – res.set() 方法


res.set() 方法可用於將響應的 HTTP 標頭欄位設定為 value。你還可以將一個物件作為引數來一次性設定多個欄位。

語法

res.set( field, [value] )

示例 1

建立一個名為 "resSet.js" 的檔案並複製程式碼段。建立檔案後,使用命令 "node resSet.js" 來執行此程式碼,如下例所示 −

// res.set(field, [value]) Method Demo Example

// Importing the express
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){

   // Setting the response content-type
   res.set({
      'Content-Type': 'text/html'
   });

   // Checking if content-type is set
   console.log("Content-Type is: ", res.get('Content-Type'));
   res.end();
});

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 resSet.js Server listening on PORT 3000 Content-Type is: text/html; charset=utf-8

示例 2

再看一個示例。

// res.set(field, [value]) Method Demo Example

// Importing the express
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){
   res.set({
      'Content-Type': 'application/zip'
   });
   next();
})

// Using middleware
app.get('/api', function(req, res){
   console.log("Content-Type is : ", res.get('Content-Type'));
   res.end();
});

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 resSet.js Server listening on PORT 3000 Content-Type is : application/zip

更新於: 28-Mar-2022

15 次瀏覽

開啟你的 職業

完成課程獲取認證

開始
廣告
© . All rights reserved.