-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
61 lines (47 loc) · 1.21 KB
/
index.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
const express = require("express");
const mongoose = require("mongoose");
const app = express();
require('dotenv').config()
//requireing http and socket.io dependencies
const http = require("http").Server(app);
const io = require("socket.io")(http);
const port = 3005;
app.use(express.static(__dirname));
//BodyParser MIddleware
app.use(express.urlencoded({ extended: true }));
//Json parser
app.use(express.json());
var Message = mongoose.model("Message", { name: String, message: String });
const dbUrl = process.env.DBURL
app.get("/messages", async (req, res) => {
const messageData = await Message.find().lean();
res.send(messageData);
});
app.post("/messages", async (req, res) => {
var message = new Message(req.body);
await message.save();
//
io.emit('message', req.body)
res.send(message);
});
io.on('connection', () => {
console.log('User Connected');
})
mongoose.connect(
dbUrl,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (!err) {
console.log("DB connection Successfull");
} else {
console.log(err);
console.log("DB connection failed");
}
}
);
http.listen(port, () => {
console.log(`Server Listeningf at ${port} `);
});