• Node.js Video Tutorials

Node.js - 請求物件



req 物件代表 HTTP 請求,並具有請求查詢字串、引數、正文、HTTP 標頭等的屬性。

請求物件屬性

以下是與請求物件關聯的一些屬性列表。

序號 屬性及描述
1

req.app

此屬性儲存對正在使用中介軟體的 Express 應用程式例項的引用。

2

req.baseUrl

安裝路由例項的 URL 路徑。

3

req.body

包含在請求正文中提交的資料的鍵值對。預設情況下,它是未定義的,在使用正文解析中介軟體(例如 body-parser)時填充。

4

req.cookies

使用 cookie-parser 中介軟體時,此屬性是一個包含請求傳送的 Cookie 的物件。

5

req.fresh

指示請求是否“新鮮”。它是 req.stale 的反義詞。

6

req.hostname

包含來自“Host”HTTP 標頭的主機名。

7

req.ip

請求的遠端 IP 地址。

8

req.ips

當 trust proxy 設定為 true 時,此屬性包含“X-Forwarded-For”請求標頭中指定的 IP 地址陣列。

9

req.originalUrl

此屬性類似於 req.url;但是,它保留原始請求 URL,允許您自由地重寫 req.url 以用於內部路由目的。

10

req.params

一個包含對映到命名路由“引數”的屬性的物件。例如,如果您有路由 /user/:name,則“name”屬性可用作 req.params.name。此物件預設為 {}。

11

req.path

包含請求 URL 的路徑部分。

12

req.protocol

請求協議字串,“http”或使用 TLS 請求時的“https”。

13

req.query

一個物件,其中包含路由中每個查詢字串引數的屬性。

14

req.route

當前匹配的路由,一個字串。

15

req.secure

一個布林值,如果建立了 TLS 連線則為 true。

16

req.signedCookies

使用 cookie-parser 中介軟體時,此屬性包含請求傳送的已簽名 Cookie,未簽名且已準備好使用。

17

req.stale

指示請求是否“陳舊”,並且是 req.fresh 的反義詞。

18

req.subdomains

請求域名中的子域名陣列。

19

req.xhr

一個布林值,如果請求的“X-Requested-With”標頭欄位為“XMLHttpRequest”,則為 true,表示請求是由 jQuery 等客戶端庫發出的。

請求物件方法

req.accepts(types)

req.accepts(types)

此方法根據請求的 Accept HTTP 標頭欄位檢查指定的 content types 是否可接受。以下是一些示例:

// Accept: text/html
req.accepts('html');
// => "html"

// Accept: text/*, application/json
req.accepts('html');

// => "html"
req.accepts('text/html');
// => "text/html"

req.get(field)

req.get(field)

此方法返回指定的 HTTP 請求標頭欄位。以下是一些示例:

req.get('Content-Type');
// => "text/plain"

req.get('content-type');
// => "text/plain"

req.get('Something');
// => undefined

req.is(type)

req.is(type)

如果傳入請求的“Content-Type”HTTP 標頭欄位與 type 引數指定的 MIME 型別匹配,則此方法返回 true。以下是一些示例:

// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
req.is('text/*');
// => true

req.param(name [, defaultValue])

req.param(name [, defaultValue])

此方法在存在時返回 param name 的值。以下是一些示例:

// ?name=tobi
req.param('name')
// => "tobi"

// POST name=tobi
req.param('name')
// => "tobi"

// /user/tobi for /user/:name 
req.param('name')
// => "tobi"
nodejs_express_framework.htm
廣告