move core headers to middleware file

This commit is contained in:
Anika Raemer 2025-10-07 19:39:07 +02:00
parent 760c91af56
commit 7252b072bd
2 changed files with 23 additions and 13 deletions

View file

@ -8,6 +8,7 @@ import compactRecipeRoutes from "./endpoints/CompactRecipePoint.js";
import recipeRoutes from "./endpoints/RecipePoint.js"; import recipeRoutes from "./endpoints/RecipePoint.js";
import { errorHandler } from "./middleware/errorHandler.js"; import { errorHandler } from "./middleware/errorHandler.js";
import { authentication } from "./middleware/authenticationMiddleware.js"; import { authentication } from "./middleware/authenticationMiddleware.js";
import { corsHeaders } from "./middleware/corsMiddleware.js";
dotenv.config(); dotenv.config();
@ -28,19 +29,7 @@ async function startServer() {
console.log("Migrations executed"); console.log("Migrations executed");
// Enable CORS before anything else // Enable CORS before anything else
// @todo move to middleware util app.use(corsHeaders);
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();
});
// Activate Authentication // Activate Authentication
app.use(authentication); app.use(authentication);

View file

@ -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();
}