lambda-api
lambda-api copied to clipboard
Question about api.routes()
I was searching to create the options method dynamically I foud a way but the only thing is that the feature api.routes is for debug purpose So I'm guessing there could be a better way for this
could you confirm that I may use the api.routes() call for this? of maybe suggest an other way of doing this
This function generates for all routes a list of methods in a string to the header 'Access-Control-Allow-Methods', and registers the method with path to the routing so that they exists as it should be
For now I call this function when all routes are apply'ed
function addOptionRoutes(api) {
const current_routes = api.routes();
const option_routes = {};
// transform routes to uniq path's with list of options
current_routes.forEach(route => {
(option_routes[route[1]] = option_routes[route[1]] || []).push(route[0])
})
// generate api.options function
Object.keys(option_routes).forEach(key => {
api.options(key, (request, response) => {
response.header(
'Access-Control-Allow-Methods',
option_routes[key].join(',') + ',OPTIONS'
);
response.sendStatus(200)
})
})
}
You could set cors for all routes using middleware, then return 200 for all OPTIONS requests. It wouldn't be as restrictive as checking the routes, but except for doing this for multiple wildcard routes or manually registering OPTIONS for each route, I can't think of a better way at the moment.
api.use((req,res,next) => {
res.cors({
origin: '*',
methods: 'GET, POST, OPTIONS',
maxAge: 84000000
});
next();
})
api.options( (req, res) => {
res.sendStatus(200);
});
Hi @MarioVerbelen. The easiest way to do this is just to set a global OPTIONS route so that any OPTION request will return a 200 with the correct CORS headers. You can either generate the CORS headers in this route, or do what I do, and generate them using a middleware handler.
// Default Options for CORS
api.options('/*', function(req,res) {
res.status(200).json({});
})
I now that globally is the easy way, With the function that I have now it generates it only for the routes with methods that exists I prefer the good way vs easy defaults
As I understand there is no such function for the moment, np