跳至主要內容
版本:最新 (v5.0.x)

請求 (Request)

請求

處理函式的第一個參數是 Request

Request 是 Fastify 的核心物件,包含以下欄位

  • query - 解析後的查詢字串,其格式由 querystringParser 指定
  • body - 請求的有效負載,請參閱 Content-Type Parser 以了解 Fastify 原生解析哪些請求有效負載以及如何支援其他內容類型
  • params - 符合 URL 的參數
  • headers - headers 的 getter 和 setter
  • raw - 來自 Node 核心的傳入 HTTP 請求
  • server - Fastify 伺服器實例,範圍限定在當前的封裝上下文
  • id - 請求 ID
  • log - 傳入請求的日誌實例
  • ip - 傳入請求的 IP 位址
  • ips - X-Forwarded-For 標頭中傳入請求的 IP 位址陣列,從最近到最遠排序(僅當啟用 trustProxy 選項時)
  • host - 傳入請求的主機(當啟用 trustProxy 選項時,從 X-Forwarded-Host 標頭衍生)。為了與 HTTP/2 相容,如果不存在 host 標頭,則返回 :authority
  • hostname - 傳入請求的主機,不含連接埠
  • port - 伺服器正在監聽的連接埠
  • protocol - 傳入請求的協定 (httpshttp)
  • method - 傳入請求的方法
  • url - 傳入請求的 URL
  • originalUrl - 類似於 url,這允許您在內部重新路由的情況下存取原始的 url
  • is404 - 如果請求由 404 處理程式處理,則為 true,否則為 false
  • socket - 傳入請求的底層連線
  • context - 已棄用,請改用 request.routeOptions.config。Fastify 內部物件。您不應直接使用或修改它。它對於存取一個特殊鍵很有用
    • context.config - 路由 config 物件。
  • routeOptions - 路由 option 物件
    • bodyLimit - 伺服器限制或路由限制
    • config - 此路由的 config 物件
    • method - 路由的 http 方法
    • url - 要比對此路由的 URL 路徑
    • handler - 此路由的處理程式
    • attachValidation - 將 validationError 附加到請求 (如果定義了 schema)
    • logLevel - 為此路由定義的日誌級別
    • schema - 此路由的 JSON schema 定義
    • version - 定義端點版本的 semver 相容字串
    • exposeHeadRoute - 為任何 GET 路由建立同級 HEAD 路由
    • prefixTrailingSlash - 用於決定如何處理具有前綴的路由的 / 字串
  • .getValidationFunction(schema | httpPart) - 如果已設定或快取任何指定的 schema 或 http 部分,則傳回該項目的驗證函式。
  • .compileValidationSchema(schema, [httpPart]) - 編譯指定的 schema 並使用預設 (或自訂) ValidationCompiler 傳回驗證函式。如果提供,可選的 httpPart 會轉發到 ValidationCompiler,預設為 null
  • .validateInput(data, schema | httpPart, [httpPart]) - 使用指定的 schema 驗證指定的輸入,並傳回序列化後的有效負載。如果提供了可選的 httpPart,則該函式會使用為該 HTTP 狀態碼提供的序列化程式函式。預設為 null

Headers

request.headers 是一個 getter,它傳回一個包含傳入請求標頭的物件。您可以像這樣設定自訂標頭

request.headers = {
'foo': 'bar',
'baz': 'qux'
}

此操作會將新值添加到可以透過呼叫 request.headers.bar 讀取的請求標頭中。此外,您仍然可以使用 request.raw.headers 屬性存取標準請求標頭。

注意:由於效能考量,在 找不到 路由上,您可能會看到我們會在標頭上新增一個額外的屬性 Symbol('fastify.RequestAcceptVersion')

fastify.post('/:params', options, function (request, reply) {
console.log(request.body)
console.log(request.query)
console.log(request.params)
console.log(request.headers)
console.log(request.raw)
console.log(request.server)
console.log(request.id)
console.log(request.ip)
console.log(request.ips)
console.log(request.host)
console.log(request.hostname)
console.log(request.port)
console.log(request.protocol)
console.log(request.url)
console.log(request.routeOptions.method)
console.log(request.routeOptions.bodyLimit)
console.log(request.routeOptions.method)
console.log(request.routeOptions.url)
console.log(request.routeOptions.attachValidation)
console.log(request.routeOptions.logLevel)
console.log(request.routeOptions.version)
console.log(request.routeOptions.exposeHeadRoute)
console.log(request.routeOptions.prefixTrailingSlash)
console.log(request.routeOptions.logLevel)
request.log.info('some info')
})

.getValidationFunction(schema | httpPart)

透過使用提供的 schemahttpPart 呼叫此函式,它將傳回可用於驗證各種輸入的 validation 函式。如果使用提供的任何輸入都找不到序列化函式,則返回 undefined

此函式具有屬性 errors。上次驗證期間遇到的錯誤會被指派給 errors

const validate = request
.getValidationFunction({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null

// or

const validate = request
.getValidationFunction('body')
console.log(validate({ foo: 0.5 })) // false
console.log(validate.errors) // validation errors

有關如何編譯驗證函式的更多資訊,請參閱.compileValidationSchema(schema, [httpStatus])

.compileValidationSchema(schema,[httpPart])

此函式將編譯驗證 schema 並傳回可用於驗證資料的函式。傳回的函式(又名驗證函式)是透過使用提供的 SchemaController#ValidationCompiler 編譯的。使用 WeakMap 來快取此項,減少編譯呼叫。

如果提供了可選參數 httpPart,則會直接轉發到 ValidationCompiler,因此如果為路由提供了自訂的 ValidationCompiler,則可以使用它來編譯驗證函式。

此函式具有屬性 errors。上次驗證期間遇到的錯誤會被指派給 errors

const validate = request
.compileValidationSchema({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
})
console.log(validate({ foo: 'bar' })) // true
console.log(validate.errors) // null

// or

const validate = request
.compileValidationSchema({
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}, 200)
console.log(validate({ hello: 'world' })) // false
console.log(validate.errors) // validation errors

請注意,使用此函式時應小心,因為它會根據提供的 schema 快取編譯的驗證函式。如果提供的 schema 已變異或更改,驗證函式將不會偵測到 schema 已被變更,並且例如它會重複使用先前編譯的驗證函式,因為快取是基於先前提供的 schema (物件) 的參考。

如果需要變更 schema 的屬性,請始終選擇建立全新的 schema (物件),否則實作將無法從快取機制中受益。

使用以下 schema 作為範例

const schema1 = {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}

不應該這樣做

const validate = request.compileValidationSchema(schema1)

// Later on...
schema1.properties.foo.type. = 'integer'
const newValidate = request.compileValidationSchema(schema1)

console.log(newValidate === validate) // true

應該這樣做

const validate = request.compileValidationSchema(schema1)

// Later on...
const newSchema = Object.assign({}, schema1)
newSchema.properties.foo.type = 'integer'

const newValidate = request.compileValidationSchema(newSchema)

console.log(newValidate === validate) // false

.validateInput(data,[schema | httpStatus], [httpStatus])

此函式將根據提供的 schema 或傳遞的 HTTP 部分驗證輸入。如果同時提供兩者,則 httpPart 參數將優先。

如果給定的 schema 沒有驗證函式,則將會編譯新的驗證函式,並在提供的情況下轉發 httpPart

request
.validateInput({ foo: 'bar'}, {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}) // true

// or

request
.validateInput({ foo: 'bar'}, {
type: 'object',
properties: {
foo: {
type: 'string'
}
}
}, 'body') // true

// or

request
.validateInput({ hello: 'world'}, 'query') // false

有關如何編譯驗證 schema 的更多資訊,請參閱 .compileValidationSchema(schema, [httpStatus])