I'm working to get a static website to call API gateway using CORS. I've got the code below running using SAM local, but I'm getting the following CORS error trying to call my API with jQuery from my static website (hosted locally):
Failed to load http://localhost:3000/notify: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
My template.yaml
:
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Api:
# enable CORS; to make more specific, change the origin wildcard
# to a particular domain name, e.g. "'www.example.com'"
Cors: "'*'"
Parameters:
RecaptchaSecret:
Type: String
Resources:
NotifierFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: notifier/build
Handler: app.lambda_handler
Runtime: python3.6
Environment:
Variables:
PARAM1: VALUE
Events:
Notify:
Type: Api
Properties:
Path: /notify
Method: post
Outputs:
NotifierApi:
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/notify/"
NotifierFunction:
Value: !GetAtt NotifierFunction.Arn
NotifierFunctionIamRole:
Value: !GetAtt NotifierFunctionRole.Arn
My understanding of the Globals
section in SAM is that it should apply the Api
field to my (inferred) API gateway.
I've seen a few examples of CORS with API gateway online where others have utilized standard API gateway templates, and some where people have used SAM in addition to a swagger file, but I've been unable to see a successful example of someone getting CORS to work using SAM without a swagger file (see below references). I feel like I must be missing something obvious!
I'm using a regular POST request from jQuery, I can post my front end code, or the "compiled" CloudForamtion as well if it's helpful.
Any help is very appreciated!
Cheers :)
References I've looked at:
Here is my function code:
import json
import boto3
import requests
def lambda_handler(event, context):
print "REACHED"
print event
ip = requests.get('http://checkip.amazonaws.com/')
return {
"statusCode": 200,
"headers": {"Access-Control-Allow-Origin": "*"},
"body": json.dumps({
'message': 'hello world',
'location': ip.text.replace('\n', ''),
})
}