Express.js – req.is() 方法


req.is() 方法用於返回匹配的內容型別。它返回匹配的內容型別,條件是傳入請求的 "Content-type" HTTP 標頭與 type 引數所指定 MIME type 匹配。如果請求沒有內容主體,則返回 NULL,否則返回 False。

語法

req.is( type )

type 引數獲取要匹配的內容型別的輸入。例如,html、text/html、text/* 等。

示例 1

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

// req.is() 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
app.get('/', function (req, res) {
   console.log(req.is('application/json'));
   res.end();
});

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

透過 GET 請求訪問以下端點 −

https://:3000/

並將 content-type 設定為 'application/json',也不要將 request 主體留空,因為一個空的 request 主體會返回 'NULL' 作為響應。

輸出

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

示例 2

我們來看另一個示例。

// req.is() 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
app.get('/', function (req, res) {
   console.log(req.is('text/*'));
   res.end();
});

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

透過 GET 請求訪問以下端點 −

https://:3000/

並將 content-type 設定為 'text/*' 以外的任何內容,也不要將 request 主體留空,因為一個空的 request 主體會返回 'null' 作為響應。

輸出

C:\home
ode>> node req.js Server listening on PORT 3000 false

更新於: 2022 年 3 月 28 日

382 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告
© . All rights reserved.