

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

# 在 CloudFront Functions 檢視器請求中使用鍵/值對
<a name="example_cloudfront_functions_kvs_key_value_pairs_section"></a>

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

------
#### [ JavaScript ]

**適用於 CloudFront Functions 的 JavaScript 執行時期 2.0 功能**  
 GitHub 上提供更多範例。尋找完整範例，並了解如何在 [CloudFront Functions 範例](https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/kvs-key-value-pairs)儲存庫中設定和執行。

```
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-general-information-section.md)。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。