serverless icon indicating copy to clipboard operation
serverless copied to clipboard

CORS is not working and doesn't support httpAPI

Open MeRahulAhire opened this issue 5 years ago • 9 comments

According to this guide by Alex Debrie

I implemented my serverless.yml


functions:
  hello:
    handler: handler.fileUpload
    events:
      - http:
          path: /sendfile
          method: post
          cors: true

and lambda function as

module.exports.fileUpload = async (event) => {
  const body = JSON.stringify(event.body);
  	return {
    statusCode: 200,
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Headers" : "*",
    },
    body: body,
  }
};

I deployed it and it works on postman but not in browser since I'm trying in my local machine giving me the error below


Access to XMLHttpRequest at 'https://{uniqueString}.amazonaws.com/sendfile' from origin 'http://localhost:5500' 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.

what should I do to get this working?

And one more thing is that the CORS method described in that blog doesn't works for httpAPI and gives me this warning :

 Configuration warning at 'functions.hello.events[0].httpApi': unrecognized property 'cors'

if I happen to use it in following way

functions:
  hello:
    handler: handler.fileUpload
    events:
      - httpApi:
          path: /sendfile
          method: post
          cors: true

MeRahulAhire avatar Feb 20 '21 12:02 MeRahulAhire

Hello @MeRahulAhire :wave:

As for the first part - I think this is more suited to be discussed on our Slack or forum -https://forum.serverless.com/ as I'm not sure if this is a bug with the Framework or with your configuration - you might also want to checkout our docs for that https://www.serverless.com/framework/docs/providers/aws/events/apigateway/#enabling-cors

As for the httpApi - the configuration is a bit different - please refer to our docs: https://www.serverless.com/framework/docs/providers/aws/events/http-api/#cors-setup

Please let me know if you feel like we still might have a bug in the Framework that should be fixed, otherwise, let's close this issue as it's intended for bugs and enhancement proposals.

Thanks :bow:

pgrzesik avatar Feb 22 '21 08:02 pgrzesik

Hi @pgrzesik, sorry for late response. I was engaged in other stuff but anyways the error is still there in Browser whether you use CORS or not in serverless.yml.Its working in postman with/without any CORS

Document - Google Chrome 25-02-2021 15_16_06_LI (2)

MeRahulAhire avatar Feb 25 '21 09:02 MeRahulAhire

Hello @MeRahulAhire - I did not manage to reproduce you issue with the exact same example you've posted both with using cURL as well as calling with fetch from the browser. Maybe there's a configuration problem with how you're calling your endpoint from the browser? Anyway - I believe it's not an issue with the framework but with your individual configuration - in this case, I think it would be best to move to our forum or to Slack.

pgrzesik avatar Feb 26 '21 08:02 pgrzesik

@pgrzesik I think I got what actually the issue is. the CORS property in serverless.yml wont work alone. You do need a headers in lambda function and ironically what I saw is whenever any error occurs it just throws CORS error in browser regardless of what it actually was. I think I do need to implement error handling correctly

MeRahulAhire avatar Feb 27 '21 10:02 MeRahulAhire

@pgrzesik

I'm trying to "fine tune" cors as described in https://www.serverless.com/framework/docs/providers/aws/events/http-api/#cors-setup, except I'm using a typescript serverless configuration file and the type definitions are complaining.

Is it not possible to do with the typescript version yet?

I'm using latest type definitions from @types/serverless

Screen Shot 2021-07-15 at 3 54 06 PM

brothatru avatar Jul 15 '21 22:07 brothatru

Hello @brothatru - you might want to try: https://www.npmjs.com/package/@serverless/typescript - I'm not sure if the definitions in types repo are up-to-date at this point. The ones from linked repository are generated based on our validation schema so they should be accurate.

pgrzesik avatar Jul 16 '21 07:07 pgrzesik

@pgrzesik Awesome @serverless/typescript package solves the issue! Thanks so much!

brothatru avatar Jul 16 '21 19:07 brothatru

Happy to hear it helped to solve your problem @brothatru :raised_hands:

pgrzesik avatar Jul 19 '21 07:07 pgrzesik

I don't know if anyone else is still having this issue, but I was able to get this to work by doing this 3 steps

  1. Adding preflight cors handlers
    // Handle preflight CORS request
    if (event.httpMethod === 'OPTIONS') {
        return {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Methods': 'OPTIONS,POST',
                'Access-Control-Allow-Headers': 'Content-Type',
                'Access-Control-Allow-Credentials': 'true',
            },
            body: JSON.stringify({}),
        };
    }
  1. Ensuring that all API responses return the access control headers alongside the response
        return {
            statusCode: 200,
            headers: {
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Credentials': 'true',
            },
            body: JSON.stringify({ message: 'Contact Form data stored successfully' })
        };
  1. I changed the serverless.yml function handler event from httpApi to http

from httpApi

functions:
  contact:
    handler: contact.handler
    events:
      - httpApi:
          path: /contact
          method: post
          cors: true 

to http

functions:
  contact:
    handler: contact.handler
    events:
      - http:
          path: /contact
          method: post
          cors: true 

oniseun avatar Jun 11 '24 22:06 oniseun