

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 在 CloudFront 函数查看器请求中使用键值对
<a name="cloudfront_example_cloudfront_functions_kvs_key_value_pairs_section"></a>

以下代码示例显示了如何在 CloudFront 函数查看器请求中使用键值对。

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

**JavaScript CloudFront 函数的运行时 2.0**  
 还有更多相关信息 GitHub。在 Functions 示例存储库中查找完整的[示例](https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/kvs-key-value-pairs)并学习如何设置和运行。CloudFront 

```
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;
}
```

------