Access to fetch from origin has been blocked by CORS policy – AWS SAM Local

Hi everyone,

I’ve been using AWS SAM local lately and ran into a bit of an issue with CORS. It took a looong time to find a solution that worked for all of my local scenarios so hopefully this will be able to help someone else out.

Access to fetch at 'http://127.0.0.1:3000' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

The error above is fairly typical when working with APIs. The request will work from tools such as postman and fiddler but browsers will block it. These are a few good links that explain why CORS is necessary:
https://medium.com/@electra_chong/what-is-cors-what-is-it-used-for-308cafa4df1a
https://stackoverflow.com/a/29167709/522859

As for the solution, add the following to your template.yml:

  PreFlightFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: functions/generic/cors.getPreflightHandler
      Runtime: nodejs8.10
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /pages
            Method: options
            RestApiId: !Ref XXXApi
            Auth:
              Authorizer: NONE

If you haven’t already defined your api in your template.yml file there is a default/omitted one created for you. There are a few examples on the AWS github: https://github.com/awslabs/serverless-application-model/blob/release/v1.8.0/examples/2016-10-31/api_cognito_auth/template.yaml

The next thing to do is to create a handler for the options request:


/* Handles retrieving a specific page */
exports.getPreflightHandler = async (event, context, callback) => {
    callback(null, { body: {} }, headers: { 'content-type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token', 'Access-Control-Allow-Methods': 'OPTIONS,GET,POST,PUT,PATCH,DELETE', 'Access-Control-Allow-Credentials': true }, statusCode: 200 })
};

I’ve moved all mine out to some helper methods but the above should be enough to get it working for you. Hopefully the AWS team will have a simpler solution soon but if you run into any issues in the meantime please let me know!

Error: Invalid value for “–parameter-overrides”: ParameterKey=TABLE_NAME,ParameterValue=CatBreeds is not in valid format. It must look something like ‘ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro’ – AWS SAM CLI

Hi everyone,

I ran into the following error while using the AWS SAM Cli:

Error: Invalid value for "--parameter-overrides": ParameterKey=PURPLE_FROG,ParameterValue=CatBreeds is not in valid format. It must look something like 'ParameterKey=KeyPairName,ParameterValue=MyKey ParameterKey=InstanceType,ParameterValue=t1.micro'

This is the command I was running:

sam local start-api --parameter-overrides "ParameterKey=PURPLE_FROG,ParameterValue=CatBreeds"

The error message is unfortunately very misleading. After a fair bit of testing I found that the cause is actually the underscore in the parameter key and has nothing to do with the command format. Renaming all of the parameters to something like “PURPLEFROG” works.

Cheers,
Chris

Create DynamoDB Table – AWS CLI

Hi everyone,

A quick example of how to create a dynamodb table using the AWS CLI:

aws dynamodb create-table --table-name CatBreeds --attribute-definitions AttributeName=CatBreedId,AttributeType=S --key-schema AttributeName=CatBreedId,KeyType=HASH --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5

For more info the following AWS page helped me: https://docs.aws.amazon.com/cli/latest/reference/dynamodb/create-table.html

An error occurred (UnrecognizedClientException) when calling the CreateFunction operation: The security token included in the request is invalid.

Hi everyone,

I ran into the following error today while attempting to create a Lambda function using the CLI:

An error occurred (UnrecognizedClientException) when calling the CreateFunction operation: The security token included in the request is invalid.

The first thing to check is that your aws config is setup correctly. For me this is under c:userschris-pc.aws.

If that looks fine, double check that the associated user has the correct rights by viewing the IAM page in the server console: https://console.aws.amazon.com/iam/home

Finally, ensure that the user has programmatic access and that the keys match those in your config.

AWS CLI Copy from Bucket – An error occurred (AccessDenied) when calling the CopyObject operation: Access Denied

Hi everyone,

I ran into the following error while trying to copy files from one bucket to another using the AWS CLI:

An error occurred (AccessDenied) when calling the CopyObject operation: Access Denied

Thankfully this one is pretty self-explanatory. My user was missing the permissions required to view the bucket.

To see your user: aws configure list
To add permissions: view the IAM Management Console

Thanks,
Chris

AWS CLI Copy to Bucket – Could not connect to the endpoint URL

Hi everyone,

I ran into the following error while attempting to copy files to a bucket via the AWS CLI:

The solution turned out to be pretty straight-forward. The region on the cli-config was set incorrectly. For example, mine was set to “Sydney” instead of “ap-southeast-2”. Type “aws configure list” to check what yours is set to.

Thanks to the following stackoverflow post for the info: https://stackoverflow.com/a/40411174/522859