在 CloudFront Functions 檢視器請求中使用鍵/值對
下列程式碼範例示範如何在 CloudFront Functions 檢視器請求中使用鍵/值對。
- JavaScript
-
- 適用於 CloudFront Functions 的 JavaScript 執行時期 2.0 功能
-
注意
GitHub 上提供更多範例。尋找完整範例,並了解如何在 CloudFront Functions 範例
儲存庫中設定和執行。 import cf from 'cloudfront'; // This fails if there is no key value store associated with the function const kvsHandle = cf.kvs(); // Remember to associate the KVS with your function before referencing KVS in your code. // https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/kvs-with-functions-associate.html async function handler(event) { const request = event.request; // Use the first segment of the pathname as key // For example http(s)://domain/<key>/something/else const pathSegments = request.uri.split('/') const key = pathSegments[1] try { // Replace the first path of the pathname with the value of the key // For example http(s)://domain/<value>/something/else pathSegments[1] = await kvsHandle.get(key); const newUri = pathSegments.join('/'); console.log(`${request.uri} -> ${newUri}`) request.uri = newUri; } catch (err) { // No change to the pathname if the key is not found console.log(`${request.uri} | ${err}`); } return request; }
如需完整的 AWS SDK 開發人員指南和程式碼範例清單,請參閱 以 AWS SDK 使用 CloudFront。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。
選取更接近檢視器的原始伺服器
驗證簡易字符