From c0c0085294101cb4813a5d11fc8dda134b807b11 Mon Sep 17 00:00:00 2001 From: buzz-lightsnack-2007 <73412182+buzz-lightsnack-2007@users.noreply.github.com> Date: Sun, 6 Apr 2025 15:07:42 +0800 Subject: [PATCH] modify web server index --- index.js | 51 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/index.js b/index.js index e565ee0..823c7ce 100644 --- a/index.js +++ b/index.js @@ -1,18 +1,45 @@ -const express = require('express') -const app = express() -const cors = require('cors') -require('dotenv').config() +/* Import modules */ +require('dotenv').config(); +const express = require('express'); +const cors = require('cors'); +const app = express(); -app.use(cors()) -app.use(express.static('public')) -app.get('/', (req, res) => { - res.sendFile(__dirname + '/views/index.html') -}); +const MainAPI = require('./scripts/API.JS'); +class WebServer { + // Basic Configuration + static port = process.env.PORT || 3000; + + /* + Initiate the web server. + @param {function} callback - The callback run before activating the server + */ + constructor(callback) { + app.use(cors({ optionsSuccessStatus: 200 })); // some legacy browsers choke on 204 + // app.use(cors()); + + this.#setDefaults(); + (callback) ? this[`activity`] = callback() : null; + var listener = app.listen(WebServer.port, () => { + console.log(`Active on port ${listener.address().port}.`); + }); + } + /* Configure the default responses for the web server. */ + #setDefaults() { + app.use(WebServer.paths['assets'], express.static(__dirname + WebServer.paths['assets'])); + app.get("/", function (REQUEST, RESPONSE) { + RESPONSE.sendFile(__dirname + WebServer[`paths`][`default`]); + }); + } + + static paths = { + "assets": "/public", + "default": '/views/index.html' + } +} + +new WebServer(() => {return (new MainAPI(app))}); -const listener = app.listen(process.env.PORT || 3000, () => { - console.log('Your app is listening on port ' + listener.address().port) -})