将跨源资源共享 (CORS) 标头添加到响应 - Amazon CloudFront

将跨源资源共享 (CORS) 标头添加到响应

以下查看器响应函数在响应未包含 Access-Control-Allow-Origin HTTP 标头时,将此标头添加到响应中。此标头属于跨源资源共享 (CORS) 的一部分。该标头的值 (*) 告诉 Web 浏览器允许来自任何源的代码访问此资源。有关更多信息,请参阅 MDN Web Docs 网站上的 Access-Control-Allow-Origin

在 GitHub 上查看此示例

JavaScript runtime 2.0
async function handler(event) { const request = event.request; const 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; }
JavaScript runtime 1.0
function handler(event) { var response = event.response; var headers = response.headers; // 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 (!headers['access-control-allow-origin']) { headers['access-control-allow-origin'] = {value: "*"}; console.log("Access-Control-Allow-Origin was missing, adding it now."); } return response; }