0

我的用例要求我的应用在错误响应为 401 时返回 CORS 标头。

AWS 去年添加了此功能(请参阅此内容)。可以使用 Cloudformation 和 Swagger 模板来完成,但我不确定是否可以使用 Chalice。

4

1 回答 1

0

我通过使用 python 脚本解决了我的问题,该脚本为 401 响应添加了 CORS 标头并重新部署了 API。这种重新部署 API 需要一两秒钟,因为它不必像 Chalice 那样部署所有 Lambda。

部署.sh

#!/usr/bin/env bash

cd services
A="$(chalice deploy --stage $1)"
cd ..
python update_api_response_headers.py "$A" "$1"

update_api_response_headers.py

import boto3
import sys
import re

if len(sys.argv) != 3:
    print("usage: python script.py <CHALICE_DEPLOYMENT_RESULT> <STAGE>")
    exit()

search = re.search('URL: https:\\/\\/([a-zA-Z0-9]+).+', sys.argv[1])
api_id = search.group(1)
print(api_id)
if not api_id:
    print(sys.argv[1])
    exit()
client = boto3.client('apigateway')

response = client.put_gateway_response(
    restApiId=api_id,
    responseType='UNAUTHORIZED',
    statusCode='401',
    responseParameters={
        "gatewayresponse.header.Access-Control-Allow-Origin": "'*'",
        "gatewayresponse.header.Access-Control-Allow-Headers": "'*'"
    }
)
response = client.create_deployment(
    restApiId=api_id,
    stageName=sys.argv[2])

print(sys.argv[1])

服务文件夹包含我的圣杯应用程序。deploy.shupdate_api_response_headers.py位于 chalice 应用程序的上一层。要部署应用程序,我只需使用:

./deploy.sh stage_name
于 2018-12-10T21:28:41.063 回答