解决CORS错误的一种方法是在API Gateway提供的选项中启用CORS,或者在Lambda中通过为响应添加适当的CORS header来解决该问题。
以下是为Lambda响应添加CORS header的示例:
import json
def lambda_handler(event, context):
response = {
'statusCode': 200,
'headers': {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Methods': 'OPTIONS,POST',
'Content-Type': 'application/json'
},
'body': json.dumps('Hello from Lambda!')
}
return response
在这个示例中,我们在响应header中添加了Access-Control-Allow-Origin
、Access-Control-Allow-Headers
和Access-Control-Allow-Methods
,来允许跨源请求。您可以修改这些header来适应您的需求。
如果您使用了API Gateway的选项来启用CORS,则不需要在Lambda中添加header。