

# 向 CloudFront Functions 查看器响应事件添加 CORS 标头
<a name="example_cloudfront_functions_add_cors_header_section"></a>

以下代码示例演示了如何向 CloudFront Functions 查看器响应事件添加 CORS 标头。

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

**适用于 CloudFront Functions 的 JavaScript 运行时 2.0**  
 查看 GitHub，了解更多信息。查找完整示例，并了解如何在 [CloudFront Functions examples](https://github.com/aws-samples/amazon-cloudfront-functions/tree/main/add-cors-header) 存储库中进行设置和运行。

```
async function handler(event)  {
    var request = event.request;
    var response  = event.response;
 
    // If Access-Control-Allow-Origin CORS header is missing, add it.
    // Since JavaScript doesn't allow for hyphens in variable names, we use the dict["key"] notation.
    if (!response.headers['access-control-allow-origin'] && request.headers['origin']) {
        response.headers['access-control-allow-origin'] = {value: request.headers['origin'].value};
        console.log("Access-Control-Allow-Origin was missing, adding it now.");
    }

    return response;
}
```

------

有关 Amazon SDK 开发人员指南和代码示例的完整列表，请参阅 [将 CloudFront 与 Amazon SDK 配合使用](sdk-general-information-section.md)。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。