Express.js – res.get() 方法


res.get() 方法用來返回由欄位指定的 HTTP 頭。匹配不區分大小寫,因此返回具有所有匹配模式的頭。

語法

res.get( field )

例子 1

建立名為 “resGet.js” 的檔案,複製程式碼段。在建立檔案後,使用命令 “node resGet.js” 執行此程式碼,如下例所示:

// res.get(field) 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){

   // Setting the Content-type
   res.set({
      'Content-Type': 'application/json',
   });

   // "text/plain"
   console.log(res.get('Content-Type'));
   res.end();
});

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

透過 GET 請求訪問以下端點 - localhost:3000/api

輸出

C:\home
ode>> node resGet.js Server listening on PORT 3000 application/json; charset=utf-8

例子 2

讓我們再看一個例子。

// res.get(field) 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){
   //Setting the response
   res.set({
      'Content-Type': 'application/xml',
   });
   next();
})

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

app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

透過 GET 請求訪問以下端點 - localhost:3000/api

輸出

C:\home
ode>> node resGet.js Server listening on PORT 3000 Content-Type is: application/xml

更新於:28-3-2022

416 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.