middy
middy copied to clipboard
http-cors: allow Access-Control-Request-Method to be used
Consider a situation where you have routes where the GET method should be allowed from anywhere, but POST, PUT, DELETE should only be allowed for certain origins.
// handlers implemented: create(), get(), filter()...
const anyOrigin = cors({ origin: '*' });
const routes: Routes = [
{
method: 'GET',
path: '/data',
handler: middy().use(anyOrigin).handler(filter),
},
{
method: 'GET',
path: '/data/{id}',
handler: middy().use(anyOrigin).handler(get),
},
{
method: 'POST',
path: '/data/{id}',
handler: create,
},
];
this is great and very easy 👍 but you also need to implement the handling of pre-flight request. you can add one more route:
{
method: 'OPTIONS',
path: '/data/{proxy+}',
handler: middy()
.use(anyOrigin) // TODO: only if Access-Control-Request-Method is GET
.handler(async () => ''),
},
this allows the preflight request to allow any origin for all methods. ideally the cors options should have a requestMethods option with a list of methods. these can be used during preflight to only apply cors if the requested method is in the provided list.