serverless-http icon indicating copy to clipboard operation
serverless-http copied to clipboard

Response Headers ? Access-Control-Allow-Origin, etc

Open Cybernetixs opened this issue 5 years ago • 3 comments

From the docs I only see a couple of items that can be added to the options. Is there a way to return CORS headers, such as Access-Control-Allow-Origin ? I have a serverless app that works fine locally but even with api gateway cors enabled the headers are not being added, and the AWS documentation states that the server needs to return those headers in addition to the api gateway cors being enabled.

I tried adding the following to the sample code, but it throws an error :

const res = await handler(event, context); res['headers'] = {'Access-Control-Allow-Origin' : '*'} // added return res

Cybernetixs avatar Feb 18 '20 17:02 Cybernetixs

You have to use a cors library and configure apig to have those headers enabled. I know it's not helpful but it's unlikely it's anything in this library, its your config in the gateway and app

dougmoscrop avatar Feb 19 '20 00:02 dougmoscrop

I use this lib https://github.com/expressjs/cors in the Express template function express-starter:

const cors = require('cors');
const router = express.Router();

router.use(cors());

But the option request's header hasn't show Access-Control-Allow-Methods and Access-Control-Allow-Headers. and so is this:

const router = express.Router();

router.options('*', (req, res, next)=>{
    console.log('options:', req.headers.origin);
    res.set({
        'Access-Control-Allow-Origin': `${req.headers.origin}`,
        'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type',
    });
    res.status(200);
});

g8up avatar Jan 08 '21 14:01 g8up

How is API gateway configured? If you're using the Serverless Framework and set up CORS in YML I believe it inserts a dummy endpoint so the OPTIONS never actually hits your app code.

dougmoscrop avatar Jan 08 '21 16:01 dougmoscrop