Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
在 CloudFront Functions 查看器请求中使用键值对
以下代码示例演示了如何在 CloudFront Functions 查看器请求中使用键值对。
- JavaScript
-
- 适用于 CloudFront Functions 的 JavaScript 运行时 2.0
-
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;
}
有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 CloudFront 与 Amazon SDK 配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。