-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
85 lines (68 loc) · 1.81 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
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
83
84
85
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const jwt = require('jwt-simple')
const User = require('./models/user')
const app = new express()
app.use(cors())
app.use(bodyParser.json())
var messages = [
{message: 'welcome to coder dojo'},
{message: 'glad to be here'}
]
app.get('/', (req, res) => {
res.send('hello from server')
})
app.get('/messages', (req, res) => {
res.send(messages)
})
app.get('/users', async (req, res) => {
try{
var users = await User.find({}, '-password -__v')
res.send(users);
}
catch(err){
console.log(err)
res.sendStatus(500)
}
})
app.get('/profile/:id', async (req, res) => {
try{
var user = await User.findById(req.params.id, '-password -__v')
res.send(user);
}
catch(err){
console.log(err)
res.sendStatus(500)
}
})
app.post('/register', (req, res) => {
var userData = req.body
var user = new User(userData)
user.save((err, result) => {
if(err){
console.log(err)
res.sendStatus(500)
}
else
res.sendStatus(201)
})
})
app.post('/login', async (req, res) => {
var userData = req.body
var user = await User.findOne({email: userData.email})
if(!user || userData.password != user.password)
res.status(401).send('User email or password invalid')
var payload = {};
var token = jwt.encode(payload, '123')
res.status(200).send({token: token})
})
mongoose.connect('mongodb://coderdojo:iamcoder@ds121289.mlab.com:21289/template-database-mlab', (err) => {
if(!err){
console.log('connected to mongo')
}
})
app.listen(8000, () => {
console.log('server is now running on port 8000')
})