Return HTML from AWS API Gateway

前端 未结 2 418
你的背包
你的背包 2020-12-08 01:25

I am trying to achieve the same thing as this post, but I do not understand the reply there and don\'t have permission to ask for clarification in the comments.

I ha

相关标签:
2条回答
  • 2020-12-08 01:54

    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.

    0 讨论(0)
  • 2020-12-08 02:09

    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.

    0 讨论(0)
提交回复
热议问题