move core headers to middleware file
This commit is contained in:
parent
760c91af56
commit
7252b072bd
2 changed files with 23 additions and 13 deletions
15
src/index.ts
15
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);
|
||||
|
|
|
|||
21
src/middleware/corsMiddleware.ts
Normal file
21
src/middleware/corsMiddleware.ts
Normal 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();
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue