-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
91 lines (76 loc) · 2.34 KB
/
app.js
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const express = require("express");
const app = express();
const mainRouter = require("./routes/index");
const cors = require("cors");
require("dotenv").config();
const sequelize = require("./config/db");
const session = require('cookie-session');
const flash = require('connect-flash');
const http = require('http');
const socketIO = require('socket.io');
// Create HTTP server
const server = http.createServer(app);
// Initialize Socket.IO
const io = socketIO(server);
// Socket.IO connection handling
io.on('connection', (socket) => {
const index = io.engine.clientsCount;
console.log(`User${index} connected.`);
// Update online count for all users
io.emit('updateOnlineUsers', io.engine.clientsCount);
socket.on('disconnect', () => {
console.log(`User${index} disconnected.`);
io.emit('updateOnlineUsers', io.engine.clientsCount);
});
});
// Configure CORS with specific options
app.use(cors({
origin: true,
credentials: true
}));
// Parse JSON and URL-encoded bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Session configuration
app.use(session({
secret: 'secret-key',
resave: false,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV === 'production',
sameSite: 'lax'
}
}));
// Make flash messages available to all views
app.use(flash());
app.use((req, res, next) => {
res.locals.messages = req.flash();
next();
});
// Static files and view engine setup
app.use(express.static("public"));
app.set("view engine", "ejs");
app.set("views", "./views");
// Routes
app.use("/", mainRouter);
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
// Check if the request expects JSON
if (req.xhr || req.headers.accept.includes('application/json')) {
return res.status(500).json({
success: false,
message: 'Something went wrong!',
error: process.env.NODE_ENV === 'development' ? err.message : undefined
});
}
// For regular requests, render an error page or redirect
res.status(500).send('Something went wrong!');
});
const PORT = process.env.PORT;
server.listen(PORT, (err) => {
if (err) {
console.error("Error in running the server:", err);
}
console.log(`Server is running on http://localhost:${PORT}`);
});