在 a CloudFront Functions 檢視器請求中使用鍵值對 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

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

在 a CloudFront Functions 檢視器請求中使用鍵值對

下列程式碼範例示範如何在 a CloudFront Functions 檢視器請求中使用鍵值對。

JavaScript
JavaScript 執行期 2.0 for CloudFront Functions
注意

還有更多 on 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; }