Lambda@Edge Viewer Request返回Open Graph HTML时body无效错误如何解决?
问题根因
你返回的自定义响应结构不符合Lambda@Edge的规范要求,存在两个核心错误:
- 字段命名错误:Lambda@Edge自定义响应要求使用
status字段存储字符串类型的状态码,不识别你代码里的statusCode字段 - 缺少编码声明:直接返回字符串类型的body时,必须显式声明
bodyEncoding: "text",否则CloudFront会默认尝试将body解析为对象,触发校验失败
修复方案
直接修改buildReleaseResponse函数的返回结构即可,修正后的代码如下:
function buildReleaseResponse( request ) { const content = `<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta property="og:type" content="website" /> <meta property="og:title" content="Hello, World" /> <meta property="og:description" content="This is an Open Graph test" /> <meta property="og:image" content="https://cdn.website.com/photos/SGmzAlNmwOGpnMeijMoW9.jpg" /> <meta property="og:url" content="https://www.website.com/hello-world" /> <title>Hello, World</title> </head> <body> <h1>Open Graph Test</h1> </body> </html>`; return { status: '200', // 替换原statusCode字段,值为字符串格式 statusDescription: 'OK', headers: { "content-type": [ { "key": "Content-Type", "value": "text/html; charset=utf-8" } ] }, bodyEncoding: 'text', // 新增字段声明body为纯文本格式 body: content.toString() }; }
后续操作说明
- 代码修改完成后需要发布新的Lambda版本
- 到CloudFront的Lambda关联配置中切换到新发布的版本
- 等待CloudFront配置生效(通常需要5~10分钟)后即可正常测试
内容的提问来源于stack exchange,提问作者Raff
相关产品推荐
相关产品推荐

