在函数中使用键值对 - Amazon CloudFront
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

在函数中使用键值对

您可以在函数中使用键值存储中的键值对。

注意

对于以下代码示例,您必须使用 JavaScript 运行时 2.0。

此示例演示了一个函数,该函数使用 HTTP 请求中的 URL 内容,在键值存储中查找自定义路径。然后,CloudFront 使用该自定义路径来发出请求。此函数有助于管理作为网站一部分的多个路径。

import cf from 'cloudfront'; ​ // Declare the ID of the key value store that you have associated with this function // The import fails at runtime if the specified key value store is not associated with the function const kvsId = "a1b2c3d4-5678-90ab-cdef-EXAMPLE11111"; ​ const kvsHandle = cf.kvs(kvsId); ​ 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; }