Return HTML from AWS API Gateway

谁说我不能喝 提交于 2019-11-28 04:44:31

You're very close. The key to understanding this is realizing that whatever Python object you return will be serialized to JSON. So, if you return a string, it will be quoted and escaped to a valid JSON object. If you want the value of this string, then use the following Integration Response mapping:

#set($inputRoot = $input.path('$')) 
$inputRoot

The #set line gives $inputRoot the value of the entire JSON object your Python program returned... which is just the original string you returned before the Lambda framework converted it to JSON.

Suppose you wanted to build the response in the mapping, instead of in your program. Then, instead of returning a Python string, you could return a Python object, like so:

return {"title": "Greeting", "message": "Hello"}

Your mapping could convert that to HTML like so:

#set($inputRoot = $input.path('$')) 
<html><head><title>$inputRoot.title</title></head>
<body>$inputRoot.message</body></html>

Using a mapping that way is more useful if you're returning structured data than simple HTML, though. I'd use the first mapping above for your problem.

When using express, you can just set the header in the app like:

res.set('Content-Type', 'text/html');

When using aws-serverless-express or similar, those headers should be propagated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!