dougmoscrop / serverless-http

Use your existing middleware framework (e.g. Express, Koa) in AWS Lambda 🎉
Other
1.74k stars 167 forks source link

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

Open Cybernetixs opened 4 years ago

Cybernetixs commented 4 years ago

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

dougmoscrop commented 4 years ago

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

g8up commented 3 years ago

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);
});
dougmoscrop commented 3 years ago

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.