-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
82 lines (72 loc) · 1.92 KB
/
index.js
File metadata and controls
82 lines (72 loc) · 1.92 KB
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
const express = require('express')
const app = express();
const knex = require('./db/knex.js')
const cors = require('cors')
const bodyParser = require('body-parser')
const port = process.env.PORT || 3000
const httpServer = require('http').createServer(app)
app.set('port', port)
const server = app.listen(app.get('port'), () => console.log(`Listening on port ${port}`))
const io = require('socket.io')(server, {
cors: {
origin: '*',
allowHeaders: '*',
credentials: false,
methods: ['GET', 'POST']
}
})
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next()
})
io.on('connection', (socket) => {
socket.on('message', (data) => {
if (data) {
io.sockets.emit('change', true)
}
})
})
app.use(express.json())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : true} ))
app.use(cors())
app.get('/users', async (req, res) => {
try {
const users = await knex('users').select()
res.status(200).json(users)
} catch (error) {
res.status(500).json({ error })
}
})
app.get('/messages', async (req, res) => {
try {
const messages = await knex('messages').select()
res.status(200).json(messages)
} catch (error) {
res.status(500).json({ error })
}
})
app.post('/messages', async (req, res) => {
try {
const message = await knex('messages').insert({
message: req.body.message,
user_name: req.body.user_name
}, 'message')
res.status(201).json( { message } )
} catch (error) {
res.status(500).json( { error } )
}
})
app.post('/users', async (req, res) => {
try {
const user = await knex('users').insert({
user: req.body.user,
password: 'password'
}, 'user')
res.status(201).json( { user } )
} catch (error) {
res.status(500).json( { error } )
}
})