diff --git a/src/index.ts b/src/index.ts index d0d06fc..400a346 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import compactRecipeRoutes from "./endpoints/CompactRecipePoint.js"; import recipeRoutes from "./endpoints/RecipePoint.js"; import { errorHandler } from "./middleware/errorHandler.js"; import { authentication } from "./middleware/authenticationMiddleware.js"; +import { corsHeaders } from "./middleware/corsMiddleware.js"; dotenv.config(); @@ -28,19 +29,7 @@ async function startServer() { console.log("Migrations executed"); // Enable CORS before anything else - // @todo move to middleware util - app.use((req: Request, res: Response, next: NextFunction) => { - res.header('Access-Control-Allow-Origin', '*'); - res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'); - res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); - - // Handle preflight requests quickly - if (req.method === 'OPTIONS') { - return res.sendStatus(200); - } - - next(); - }); + app.use(corsHeaders); // Activate Authentication app.use(authentication); diff --git a/src/middleware/corsMiddleware.ts b/src/middleware/corsMiddleware.ts new file mode 100644 index 0000000..9d3f6d7 --- /dev/null +++ b/src/middleware/corsMiddleware.ts @@ -0,0 +1,21 @@ +import { Request, Response, NextFunction } from "express"; + +/** + * Add CORS header + * + * CORS (Cross-Origin Resource Sharing) must be enabled for the web app + * to communicate with the backehd + */ +export function corsHeaders (req: Request, res: Response, next: NextFunction) { + // allow requests from all sources (*) for now + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE,OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); + + // Handle preflight requests quickly + if (req.method === 'OPTIONS') { + return res.sendStatus(200); + } + + next(); + } \ No newline at end of file