tmbakk / index.js
Ruloaooa's picture
Create index.js
fb3d031 verified
import express from 'express';
import cors from 'cors';
import mongoose from 'mongoose';
import session from 'express-session';
import MongoStore from 'connect-mongo';
import dotenv from 'dotenv';
const app = express();
const PORT = 3001;
// Middleware
app.use(cors({
origin: true,
credentials: true
}));
app.use(express.json());
// MongoDB Connection
mongoose.connect('mongodb+srv://your_mongodb_uri', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// Session Configuration
app.use(session({
secret: 'your_secret_key',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: 'mongodb+srv://your_mongodb_uri'
}),
cookie: {
maxAge: 1000 * 60 * 60 * 24 // 24 hours
}
}));
// Comments Schema
const commentSchema = new mongoose.Schema({
name: String,
text: String,
song: Object,
timestamp: { type: Date, default: Date.now }
});
const Comment = mongoose.model('Comment', commentSchema);
// Routes
app.get('/api/comments', async (req, res) => {
try {
const comments = await Comment.find().sort({ timestamp: -1 });
res.json(comments);
} catch (error) {
res.status(500).json({ error: 'Error fetching comments' });
}
});
app.post('/api/comments', async (req, res) => {
try {
const comment = new Comment(req.body);
await comment.save();
res.json(comment);
} catch (error) {
res.status(500).json({ error: 'Error saving comment' });
}
});
app.listen(PORT, '0.0.0.0', () => {
console.log(`Server running on port ${PORT}`);
});