Author Topic: Problems with CORS when creating Creating API's from CloudFormation / SAM  (Read 2389 times)

0 Members and 1 Guest are viewing this topic.

Offline mrpacketheadTopic starter

  • Super Contributor
  • ***
  • Posts: 2845
  • Country: nz
  • D Size Cell
Ok, lets see if the eevblog AWS knowledge is good.. :-)

I have a lambda that looks up a DynamoDB table and returns a lists based on a value that is posted it. It is quite simple but i've run into a problem with CORS and im not sure how to fix it. I'd ideally like to be able to configure in the CF / SAM templates and just deploy it.. But i'm not sure what is stopping this from working.
The lambda is looks like this

Code: [Select]
import json
import boto3
from boto3.dynamodb.conditions import Key, Attr
from botocore.exceptions import ClientError
def lambda_handler(event, context):
    dynamodb = boto3.resource("dynamodb")
    table = dynamodb.Table('learning-values')
    _class = "widgets" 
    body = json.loads(event['body'])
    _subclass = body['widget']
        response = table.get_item(
                'class': _class,
                'subclass': _subclass
    except ClientError as e:
        item = response['Item']['data']['options']
    return {
            "statusCode": 200,
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Headers": "Content-Type",
                        "Access-Control-Allow-Methods": "OPTIONS,POST,GET"
            "body": json.dumps(
                        "message": item

I used Cloudformation to deploy the API. it creates it, and i'm able to post a value to it and get the expected list back. I have tested it using this small piece of python.

Code: [Select]
import requests, json, sys, base64
url = '' # learn11
widget = sys.argv[1]
payload = {"widget": widget}
header = {"Content-type": "application/json"}
r =, data=json.dumps(payload))#, headers=header)
items = r.json()['message']

The response I get is like this

Code: [Select]
Z:\sam\learning\sandbox\widget>py shape
['round', 'square', 'triangle', 'diamond']
Z:\sam\learning\sandbox\widget>py smell
['fowl', 'stinky', 'nothing', 'fresh-linen', 'vanilla', 'tropical', 'cut-grass']
Z:\sam\learning\sandbox\widget>py colours
['red', 'green', 'blue', 'yellow', 'grey', 'black', 'white']

When i attempt to get that same data from javascript using this html. ( either hosted on S3, or locally) I get CORS errors in the browser.

widget.html:1 Access to XMLHttpRequest at '' from origin 'null' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

Code: [Select]
<!DOCTYPE html>
<script src=""></script>
<p>Get Colours</p>
<div ng-app="myLearn" ng-controller="myLearnCtrl">
var app = angular.module('myLearn', []);
app.controller('myLearnCtrl', function($scope, $http) {
  .then(function(response) {
      $scope.message =["message"];

The template i am using to deploy from is relatively simple.

Code: [Select]
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: '
  Sample SAM Template for learning
    Timeout: 3
    EndpointConfiguration: REGIONAL
    Cors: '''*'''
    Type: AWS::Serverless::Api
      StageName: prod
    Type: AWS::Serverless::Function
      CodeUri: s3://XXXXXXX-lambda-packages/0ab6dbfb0a46f18f11e43af73ee5d578
      Handler: app.lambda_handler
      Runtime: python3.7
          Type: Api
            Path: /widget
            Method: post
              Ref: LearningAPI

On a quest to find increasingly complicated ways to blink things

Offline windsmurf

  • Frequent Contributor
  • **
  • !
  • Posts: 625
  • Country: us
I'm guessing it has to do with Boto3 configs alreadying passing credentials to aws, whereas HTML is not authenticated?


Offline mrpacketheadTopic starter

  • Super Contributor
  • ***
  • Posts: 2845
  • Country: nz
  • D Size Cell
Just needed to fix my template, so it deployed properly.
On a quest to find increasingly complicated ways to blink things

Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo