-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
50 lines (40 loc) · 1.04 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
const express = require('express');
const dotenv = require('dotenv');
const connectDB = require('./config/db');
// Students Model
const Students = require('./models/Students');
// Load env variables
dotenv.config({ path: './config/config.env' });
// Connect to MongoDB
connectDB();
const app = express();
// Body parser
app.use(express.json());
// Retrieves all students from mongoDB
app.get('/students', (req, res) => {
Students.find().then((student) => {
res.send({
success: true,
student: student,
});
});
});
// Create a student in mongoDB
app.post('/students', (req, res, next) => {
Students.create(req.body).then((student) => {
res.send({
success: true,
student: student,
});
});
});
const PORT = process.env.PORT || 8000;
const server = app.listen(PORT, () =>
console.log(` 🔥Server running on port ${PORT}🔥 `)
);
// Handle unhandled promises
process.on('unhandledRejection', (err, promise) => {
console.log(`Error: ${err.message}`);
// Close server
server.close(() => process.exit);
});