Skip to content

Instantly share code, notes, and snippets.

@asunar
Last active January 16, 2021 15:26
Show Gist options
  • Save asunar/217baca6b0fbb6860d95a0558b6b5be5 to your computer and use it in GitHub Desktop.
Save asunar/217baca6b0fbb6860d95a0558b6b5be5 to your computer and use it in GitHub Desktop.
CORS Configuration for a simple image processor
# Simple SAM template with CORS configuration for an image processor lambda
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
test
Sample SAM Template for test
Globals:
Function:
Timeout: 10
Resources:
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
CorsConfiguration:
AllowHeaders:
- x-apigateway-header
AllowMethods:
- OPTIONS
- POST
AllowOrigins:
- "*"
ProcessImageFunction:
Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
Properties:
CodeUri: processimage/
Handler: app.lambdaHandler
Runtime: nodejs12.x
Events:
UploadImageEvent:
Type: HttpApi
Properties:
Path: /upload
Method: post
ApiId: !Ref HttpApi
# this is what lambda returns
return { "status": 200, "body": events,
headers: {
"Access-Control-Allow-Headers" : "Content-Type",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS,POST,GET,PUT",
}
# Client side js calling the api endpoint
const API_ENDPOINT = 'https://xxxxxxxx.execute-api.us-west-1.amazonaws.com/Prod/upload/'
axios
.post(API_ENDPOINT, data)
.then((response) => {
}
# Result:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxxxx.execute-api.us-west-1.amazonaws.com/Prod/upload/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment