Created
February 9, 2025 20:20
-
-
Save suhailroushan13/bf5269a80da8f00d8ae0215c2dfda2b7 to your computer and use it in GitHub Desktop.
Basic app.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from "express"; | |
import fs from "fs"; | |
import path from "path"; | |
import { fileURLToPath } from "url"; | |
import config from "config"; | |
import cors from "cors"; | |
// Database connection | |
import "./utils/dbConnect.js"; | |
const __filename = fileURLToPath(import.meta.url); | |
const __dirname = path.dirname(__filename); | |
const app = express(); | |
const PORT = config.get("PORT") || 9989; | |
// CORS configuration | |
const corsOptions = { | |
origin: [ | |
"https://cs24.code.in", | |
"http://localhost:3000", | |
"https://suhailroushan.in", | |
], | |
methods: ["GET", "POST", "PUT", "DELETE"], | |
credentials: true, | |
}; | |
app.use(cors(corsOptions)); | |
// Middleware setup | |
app.use(express.json()); | |
// Use API routes | |
// Serve React build folder if exists | |
const buildPath = path.join(__dirname, "dist"); | |
if (fs.existsSync(buildPath)) { | |
app.use(express.static(buildPath)); | |
app.get("/*", (req, res) => { | |
res.sendFile(path.join(buildPath, "index.html")); | |
}); | |
} | |
// 404 handler | |
app.use((req, res) => { | |
res.status(404).send("404 - Not Found"); | |
}); | |
// Error handler | |
app.use((err, req, res, next) => { | |
console.error(err.stack); | |
res.status(500).send("500 - Internal Server Error"); | |
}); | |
// Start the server | |
app.listen(PORT, () => { | |
console.log(`Server is running on PORT 🚀 ${PORT}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment