-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
70 lines (60 loc) · 2.22 KB
/
server.js
File metadata and controls
70 lines (60 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const morgan = require('morgan');
const cors = require('cors');
// Import routes
const apiRoutes = require('./routes/api');
const webRoutes = require('./routes/web');
const app = express();
// Middleware setup
app.use(cors());
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Set view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Add path to all template renders
app.use((req, res, next) => {
const originalRender = res.render;
res.render = function(view, locals, callback) {
if (typeof locals === 'object' && locals !== null) {
locals.path = req.path;
} else if (typeof locals === 'undefined') {
locals = { path: req.path };
}
originalRender.call(this, view, locals, callback);
};
next();
});
// Mount routes
app.use('/api', apiRoutes);
app.use('/', webRoutes);
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
const statusCode = err.statusCode || 500;
res.status(statusCode).json({
error: err.message || 'Internal Server Error',
stack: process.env.NODE_ENV === 'production' ? undefined : err.stack
});
});
// Start the server only when running directly (not when imported)
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`
╔══════════════════════════════════════════════════════════╗
║ ║
║ Usagey Express Example Server ║
║ Running on http://localhost:${PORT} ║
║ ║
╚══════════════════════════════════════════════════════════╝
`);
});
}
module.exports = app;