-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
83 lines (70 loc) · 2 KB
/
server.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
// server.js
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');
require('dotenv').config();
const MONGODB_URL = process.env.MONGODB_URL;
const app = express();
app.use(bodyParser.json());
// Serve static files (like HTML, CSS) from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
// MongoDB connection
mongoose.connect(MONGODB_URL)
.then(() => console.log('Connected to MongoDB'))
.catch((error) => console.error('Error connecting to MongoDB:', error));
const taskSchema = new mongoose.Schema({
title: String,
completed: { type: Boolean, default: false },
});
const Task = mongoose.model('Task', taskSchema);
// Root route
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Add a new task
app.post('/tasks', async (req, res) => {
const task = new Task(req.body);
try {
await task.save();
res.status(201).send(task);
} catch (error) {
res.status(400).send(error);
}
});
// Get all tasks
app.get('/tasks', async (req, res) => {
try {
const tasks = await Task.find();
res.status(200).send(tasks);
} catch (error) {
res.status(500).send(error);
}
});
// Update a task
app.patch('/tasks/:id', async (req, res) => {
try {
const task = await Task.findByIdAndUpdate(req.params.id, req.body, { new: true });
if (!task) {
return res.status(404).send();
}
res.send(task);
} catch (error) {
res.status(400).send(error);
}
});
// Delete a task
app.delete('/tasks/:id', async (req, res) => {
try {
const task = await Task.findByIdAndDelete(req.params.id);
if (!task) {
return res.status(404).send();
}
res.send(task);
} catch (error) {
res.status(500).send(error);
}
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});