-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
54 lines (41 loc) · 1.17 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
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
var server = app.listen(process.env.PORT || 3001, () => {
console.log('server is running on port', server.address());
});
var http = require('http').Server(app);
var socket = require('socket.io');
var io = socket(server);
var dbURL = require('./config');
app.use(express.static("views"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect(dbURL, { useUnifiedTopology: true }, (err) => {
console.log('mongodb connected', err);
});
var Message = mongoose.model('Message',
{
name: String,
message: String
});
io.on('connection', () => {
console.log('a user is connected');
});
app.get('/messages', (req, res) => {
Message.find({}, (err, message) => {
res.send(message);
});
});
app.post('/messages', (req, res) => {
var message = new Message(req.body);
message.save((err) => {
if (err){
res.sendStatus(500);
}
/* res.status(200); */
io.emit('message', req.body)
});
});