dherault / serverless-offline

Emulate AWS λ and API Gateway locally when developing your Serverless project
MIT License
5.19k stars 796 forks source link

CORS headers missing when invoking function via aws sdk #1692

Open Dartv opened 1 year ago

Dartv commented 1 year ago

Bug Report

No CORS headers (e.g. Access-Control-Allow-Origin and Access-Control-Allow-Credentials) are present when invoking a function via aws sdk. Deployed lambda works fine.

Current Behavior Error in console Access to XMLHttpRequest at 'http://localhost:4001/2015-03-31/functions/serverless-action-exports-dev-exportTable/invocations' from origin 'http://localhost:3000' 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.

Sample Code

provider:
  name: aws
  runtime: nodejs14.x
  stage: dev
  region: us-east-1
  memorySize: 10240

functions:
  exportTable:
    handler: src/index.exportTable
    timeout: 900

plugins:
  - serverless-offline

custom:
  serverless-offline:
    lambdaPort: 4001

Expected behavior/code

CORS headers are present and no error in console.

Environment

Possible Solution

Looks like need to handle CORS here https://github.com/dherault/serverless-offline/blob/v12.0.4/src/lambda/HttpServer.js same as here https://github.com/dherault/serverless-offline/blob/v12.0.4/src/events/http/HttpServer.js#L107 Adding onPreResponse fixes the issue for me

Additional context/Screenshots