-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (56 loc) · 1.82 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
// server.js (Express 4.0)
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
app.use(express.static(__dirname)); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser()); // pull information from html in POST
app.use(methodOverride()); // simulate DELETE and PUT
var router = express.Router();
var notes = [
{id: 1, label: 'First Note', author: 'Shyam'},
{id: 2, label: 'Second Note', author: 'Brad'},
{id: 3, label: 'Middle Note', author: 'Someone'},
{id: 4, label: 'Last Note', author: 'Shyam'},
{id: 5, label: 'Really the last Note', author: 'Shyam'}
];
var lastId = 6;
router.get('/note', function(req, res) {
res.send(notes);
});
router.post('/note', function(req, res) {
var note = req.body;
note.id = lastId;
lastId++;
notes.push(note);
res.send(note);
});
router.get('/note/:id', function(req, res) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id == req.params.id) {
res.send(notes[i]);
break;
}
}
res.send({msg: 'Note not found'}, 404);
});
router.post('/note/:id', function(req, res) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].id == req.params.id) {
notes[i] = req.body;
notes[i].id = req.params.id;
res.send(notes[i]);
break;
}
}
res.send({msg: 'Note not found'}, 404);
});
router.post('/login', function(req, res) {
console.log('API LOGIN FOR ', req.body);
res.send({msg: 'Login successful for ' + req.body.username});
});
app.use('/api', router);
app.listen(8000);
console.log('Open http://localhost:8000 to access the files now'); // shoutout to the user