From b5a697181ef2f754d57f2c62e252d2e9b792d89b Mon Sep 17 00:00:00 2001 From: Juan Rojas Aktua <114270458+JuanRojasDev@users.noreply.github.com> Date: Wed, 20 Mar 2024 10:35:09 -0500 Subject: [PATCH] Optimized Express server setup and middleware configuration This commit refactors the Express server setup to improve readability and organization. It also optimizes middleware configuration and removes unnecessary comments. Additionally, it updates comments to be in English for better consistency and clarity. --- server/index.js | 52 ++++++++++++++----------------------------------- 1 file changed, 15 insertions(+), 37 deletions(-) diff --git a/server/index.js b/server/index.js index 479f500..e7f97ca 100644 --- a/server/index.js +++ b/server/index.js @@ -2,9 +2,7 @@ import express from 'express'; import dotenv from 'dotenv'; import mongoose from 'mongoose'; import cors from 'cors'; -import morgan from 'morgan'; -//routes import authRoutes from './routes/auth.js'; import podcastsRoutes from './routes/podcast.js'; import userRoutes from './routes/user.js'; @@ -12,23 +10,14 @@ import userRoutes from './routes/user.js'; const app = express(); dotenv.config(); -/** Middlewares */ +// Middleware setup app.use(express.json()); -const corsConfig = { +app.use(cors({ credentials: true, origin: true, -}; -app.use(cors(corsConfig)); -// app.use(morgan('tiny')); -// app.disable('x-powered-by'); -// app.use(function (request, response, next) { -// response.header("Access-Control-Allow-Origin", "*"); -// response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); -// next(); -// }); - -const port = process.env.PORT || 8700; +})); +// MongoDB connection const connect = () => { mongoose.set('strictQuery', true); mongoose.connect(process.env.MONGO_URL).then(() => { @@ -38,25 +27,12 @@ const connect = () => { }); }; +// Routes +app.use("/api/auth", authRoutes); +app.use("/api/podcasts", podcastsRoutes); +app.use("/api/user", userRoutes); -app.use(express.json()) -// app.enable('trust proxy'); // optional, not needed for secure cookies -// app.use(express.session({ -// secret : '123456', -// key : 'sid', -// proxy : true, // add this when behind a reverse proxy, if you need secure cookies -// cookie : { -// secure : true, -// maxAge: 5184000000 // 2 months -// } -// })); - -app.use("/api/auth", authRoutes) -app.use("/api/podcasts", podcastsRoutes) -app.use("/api/user", userRoutes) -// app.use("/api/project", projectRoutes) -// app.use("/api/team", teamRoutes) - +// Error handling app.use((err, req, res, next) => { const status = err.status || 500; const message = err.message || "Something went wrong"; @@ -64,10 +40,12 @@ app.use((err, req, res, next) => { success: false, status, message - }) -}) + }); +}); +// Listening port +const port = process.env.PORT || 8700; app.listen(port, () => { - console.log("Connected") + console.log(`Server is running on port ${port}`); connect(); -}) +});