-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
63 lines (62 loc) · 1.65 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
62
63
/* Tanımlama */
const http = require('http')
const express = require('express')
const mongoose = require('mongoose')
const ejs = require('ejs')
const bodyParser = require('body-parser')
const cookieParser = require ('cookie-parser')
const app = express()
const port = 3000;
const server = http.createServer(app)
const User = require('./models/users.js')
app.set('view engine','ejs')
app.use(express.static('public'))
app.use(cookieParser())
app.use(bodyParser.json()).use(
bodyParser.urlencoded({
extended: true,
})
);
/* Socket.io */
const { Server } = require("socket.io");
const io = new Server(server);
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
/* Mongoose Connections */
const dbURL = process.env.db;
mongoose.connect(dbURL, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => {
server.listen(port, () => {
console.log("mongoDB Bağlantı kuruldu");
});
})
.catch((err) => console.log(err));
/* Server Bağlantı */
app.get('/',(req,res)=>{
let userID = req.cookies.id;
if(userID != null){
User.findById(userID).then((UserResult)=>{
res.render(`${__dirname}/views/pages/chat.ejs`,{user:UserResult})
})
}else{
res.render(`${__dirname}/views/pages/kayıt.ejs`)
}
})
app.post('/kayit',(req,res)=>{
User.findOne({username : req.body.username}, (user,err)=>{
if(user){
res.render(`${__dirname}/views/error/kayıtlı.ejs`)
} else {
var user = new User({
username : req.body.username,
})
user.save().then((result)=>{
res.cookie("id", result._id)
res.redirect('/')
})
}
})
})