View a markdown version of this page

一般協助程式方法 - Amazon CloudFront

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

一般協助程式方法

此頁面提供 CloudFront Functions 內的其他協助程式方法。若要使用這些方法,請使用 JavaScript 執行期 2.0 建立 CloudFront 函數。

import cf from 'cloudfront';

如需詳細資訊,請參閱適用於 CloudFront Functions 的 JavaScript 執行時期 2.0 功能

edgeLocation 中繼資料

此方法需要使用 cloudfront模組。

注意

您只能將此方法用於檢視器請求函數。對於檢視器-回應函數,此方法為空。

使用此 JavaScript 物件來取得節點機場代碼、預期的區域節點快取區域或用於處理請求的 CloudFront 伺服器 IP 地址。此中繼資料僅適用於檢視器請求事件觸發。

cf.edgeLocation = { name: SEA serverIp: 1.2.3.4 region: us-west-2 }

cf.edgeLocation 物件可以包含下列項目:

name

處理請求之節點的三個字母 IATA 代碼

serverIp

處理請求之伺服器的 IPv4 或 IPv6 地址。

region

如果發生快取遺漏,預期請求使用的 CloudFront Regional Edge Cache (REC)。如果預期的 REC 無法使用,且請求使用備份 REC,則不會更新此值。這不包括正在使用的 Origin Shield 位置,除非主要 REC 和 Origin Shield 是相同的位置。

注意

當 CloudFront 設定為使用原始伺服器容錯移轉時,不會再次叫用 CloudFront Functions。如需詳細資訊,請參閱透過 CloudFront 原始伺服器容錯移轉最佳化高可用性

rawQueryString() 方法

此方法不需要 cloudFront模組。

使用 rawQueryString()方法將未剖析和未變更的查詢字串擷取為字串。

請求

function handler(event) { var request = event.request; const qs = request.rawQueryString(); }

回應

將傳入請求的完整查詢字串傳回為字串值,而不含前置 ?

  • 如果沒有查詢字串,但 ? 存在,則函數會傳回空字串。

  • 如果沒有查詢字串且 ? 不存在,則函數會傳回 undefined

案例 1:傳回完整查詢字串 (沒有前置 ?)

傳入請求 URL: https://example.com/page?name=John&age=25&city=Boston

rawQueryString() 傳回: "name=John&age=25&city=Boston"

案例 2:傳回空字串 (當 ? 存在但沒有參數時)

傳入請求 URL: https://example.com/page?

rawQueryString() 傳回: ""

案例 3:undefined傳回 (沒有查詢字串,也沒有 ?)

傳入請求 URL: https://example.com/page

rawQueryString() 傳回: undefined

logCustomData() 方法

若要使用此方法,請匯入 cloudfront模組。

使用 logCustomData()方法將自訂資料從 Amazon CloudFront 函數傳送至 CloudFront 存取日誌。資料會寫入 viewer-request-log-dataviewer-response-log-data日誌欄位,取決於函數是否與檢視器請求或檢視器回應事件相關聯。

方法接受單一字串引數。若要記錄物件,請先使用 將其JSON.stringify()轉換為字串。例如:

const resp_obj = JSON.stringify(some_obj); cf.logCustomData(resp_obj);

每個欄位最多支援 800 個位元組的資料。CloudFront 會自動將資料 URL 編碼,然後再寫入日誌欄位。在 URL 編碼之後,CloudFront 會截斷任何超過 800 位元組的資料。如果您的函數在單一執行中呼叫logCustomData()多次,CloudFront 只會使用最後一個值。

將欄位新增至您的日誌組態

若要在 CloudFront 存取日誌中接收此資料,您必須將 viewer-request-log-dataviewer-response-log-data 欄位新增至即時日誌組態或標準記錄 (v2) 設定。CloudFront Functions 不支援內嵌存在點 (POPs) 的自訂資料記錄。

與 console.log() 的差異

logCustomData() 方法不會console.log()取代 CloudFront Functions。使用 console.log() 將日誌行傳送至 Amazon CloudWatch Logs。使用 cf.logCustomData() 將自訂資料寫入 CloudFront 存取日誌 (即時日誌標準記錄 (v2))。您可以在相同的 函數中使用這兩種方法。如需詳細資訊,請參閱 CloudFront Functions 日誌

方法使用下列語法:

cf.logCustomData(String);
範例在檢視器請求函數中記錄標頭
import cf from 'cloudfront'; function handler(event) { var request = event.request; // Check if the debug header exists, if so log it if (request.headers['x-debug-header']) { // Log the debug header value cf.logCustomData("debug header found: " + request.headers['x-debug-header'].value); } return request; }