Express.js - req.accepts() 方法


req.accepts() 方法檢查請求的 Accept HTTP 標頭欄位是否可以接受指定的內容型別。此方法返回最佳匹配,如果指定的任何內容型別都不可以接受,則返回 False。

型別值可以是 MIME 型別(例如 application/json),也可以是副檔名(例如 json)。

語法

req.accepts( types )

示例 1

"reqAccepts.js" 名稱建立一個檔案,並複製以下程式碼段。建立檔案後,使用命令 "node reqAccepts.js" 執行此程式碼,如下面的示例所示 -

// req.accepts() Method Demo Example
// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint with req.accepts() fn
app.get('/', function (req, res) {
   console.log(req.get('Accept'));
   console.log(req.accepts('application/json'));
   res.end();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

使用 GET 請求訪問端點 localhost:3000/,並將內容型別設定為 'application/json',並將 Accept 設定為 'application/json'

C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 application/json application/json

示例 2

讓我們看另一個示例。

// req.accepts() Method Demo Example
// Importing the express module
var express = require('express');

// Initializing the express and port number
var app = express();
var PORT = 3000;

// Defining an endpoint with req.accepts() fn
app.get('/', function (req, res) {
   console.log(req.get('Accept'));
   console.log(req.accepts('text/html'));
   res.end();
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

輸出

使用 GET 請求訪問端點 localhost:3000/,並將 內容型別設定為 'text/plain',並將 Accept 設定為 'text/plain'

C:\home
ode>> node reqAccepts.js Server listening on PORT 3000 text/plain false

更新於: 06-4 月-2022

717 次瀏覽

職業生涯起步

完成課程獲得認證

入門
廣告
© . All rights reserved.