question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Feature Request] CORS Support in start-api

See original GitHub issue

Full disclosure, this is my first attempt at working with a SAM template so it’s likely I’m doing something wrong, but I can’t get CORS working for the life of me. My functions work when I hit the endpoints using Insomnia, but when trying to hit it from my app, I get a 404 on the options request. Also, when I run sam local start-api, I get a message saying WARNING: Could not find function for [OPTIONS] to /login resource right above a message saying Mounting index.login (nodejs6.10) at http://127.0.0.1:3000/login [POST]
Below is my template.yaml. I attempted to follow the example here, but still no luck.

However, if I remove the “options” part of the swagger definition, I don’t get the OPTIONS warning.

            options:
              consumes:
              - application/json
              produces:
              - application/json
              responses:
                '200':
                  description: 200 response
                  headers:
                    Access-Control-Allow-Origin:
                      type: string
                    Access-Control-Allow-Methods:
                      type: string
                    Access-Control-Allow-Headers:
                      type: string
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: 200
                    responseParameters:
                      method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                      method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                passthroughBehavior: when_no_match
                requestTemplates:
                  application/json: "{\"statusCode\": 200}"
                type: mock

Any help / suggestions would be greatly appreciated

AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'

Parameters:
  TableName:
    Default: <TableName>
    Type: String
  FunctionNamePrefix:
    Default: <TableName>
    Type: String
  Secret:
    Default: ""
    Type: String
  AppConfigReadCapacity:
    Default: 5
    Type: Number
  AppConfigWriteCapacity:
    Default: 5
    Type: Number
  AppConfigPrimaryKey:
    Default: id
    Type: String
  Env:
    Default: dev
    Type: String
  S3Bucket:
    Default: <S3Bucket>
    Type: String

Resources:
  EnterpriseApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: dev
      DefinitionBody:
        swagger: '2.0'
        info:
          title: 'API Gateway Endpoints'
        basePath: '/dev'
        schemes:
          - 'https'
        paths:
          "/login":
            post:
              x-amazon-apigateway-integration:
                httpMethod: POST
                type: aws_proxy
                uri: "arn:aws:apigateway:${awsRegion}lambda:path/2015-03-31/functions/arn:aws:lambda:${awsRegion}l:${awsAccount}:function:${function}/invocations"
                responses: {}
                passthroughBehavior: when_no_match
            options:
              consumes:
              - application/json
              produces:
              - application/json
              responses:
                '200':
                  description: 200 response
                  headers:
                    Access-Control-Allow-Origin:
                      type: string
                    Access-Control-Allow-Methods:
                      type: string
                    Access-Control-Allow-Headers:
                      type: string
              x-amazon-apigateway-integration:
                responses:
                  default:
                    statusCode: 200
                    responseParameters:
                      method.response.header.Access-Control-Allow-Methods: "'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'"
                      method.response.header.Access-Control-Allow-Headers: "'Content-Type,Authorization,X-Amz-Date,X-Api-Key,X-Amz-Security-Token'"
                      method.response.header.Access-Control-Allow-Origin: "'*'"
                passthroughBehavior: when_no_match
                requestTemplates:
                  application/json: "{\"statusCode\": 200}"
                type: mock

  LoginFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.login
      Runtime: nodejs6.10
      CodeUri: 's3://${s3Bucket}/${s3Folder}/test.zip'
      FunctionName:
        Fn::Join:
          - "-"
          -
            - Ref: FunctionNamePrefix
            - login
      Description: ''
      Timeout: 30
      Environment:
        Variables:
          TABLE_NAME:
            Ref: TableName
          NODE_ENV:
            Ref: Env
          S3_BUCKET: <BucketName>
          SECRET:
            Ref: Secret
          AWS_PROFILE:
            Ref: AwsProfile
          POSTGRES_HOST:
            Ref: PostgresHost
          POSTGRES_DB:
            Ref: PostgresDb
          POSTGRES_USER:
            Ref: PostgresUser
          POSTGRES_PASSWORD:
            Ref: PostgresPassword
          POSTGRES_DB:
            Ref: PostgresDb
          API_Key:
            Ref: ApiKey
      Events:
        LoginResource:
          Type: Api
          Properties:
            Path: /login
            Method: post
            RestApiId:
              Ref: EnterpriseApi

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:22
  • Comments:45 (3 by maintainers)

github_iconTop GitHub Comments

29reactions
johnc44commented, Apr 16, 2019

It occurred to me that a simpler solution than the lambda posted above would probably be to simply proxy all requests to sam.

I did a (very) quick Google and found this: https://www.npmjs.com/package/local-cors-proxy

To make this work, I simply need to start SAM locally, then do this:

npm install local-cors-proxy npx lcp --proxyUrl http://localhost:3000/

(where “3000” is the port SAM is running)

I then reference the API using http://localhost:8010/proxy/.

Not as good as a fully integrated SAM solution, but at least it doesn’t involve any code changes.

22reactions
skylerrichtercommented, Jul 24, 2018

@rabowskyb does this example work with SAM CLI?

This does not seem to do anything for me when using sam local start-api

Globals:
  Api:
    Cors:
      AllowMethods: "'*'"
      AllowHeaders: "'*'"
      AllowOrigin: "'*'"
Read more comments on GitHub >

github_iconTop Results From Across the Web

CorsConfiguration - AWS Serverless Application Model
Manage cross-origin resource sharing (CORS) for your API Gateway APIs. ... String containing the number of seconds to cache CORS Preflight request.
Read more >
What Is a CORS Error and How to Fix It (3 Ways) - Bannerbear
A CORS error is common when making an HTTP request to another origin. You can get rid of it using one of the...
Read more >
Configure Cross-Origin Resource Sharing
To enable CORS support in API Gateway, you must first add a CORS profile in Policy Studio: In the Policy Studio tree, select...
Read more >
Authoritative guide to CORS (Cross-Origin Resource Sharing ...
Without features like CORS, websites are restricted to accessing resources ... A simple request is a CORS request that doesn't require a ...
Read more >
Configuring Cors For Sam. API Works With Postman, But Not Angular
Use Postman to call a REST API Enabling CORS support for Lambda or HTTP non-proxy ... sam local start-api Please follow #323 for...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found