-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (60 loc) · 1.45 KB
/
Copy pathserver.js
File metadata and controls
66 lines (60 loc) · 1.45 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
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
var PORT = process.env.PORT || 3000;
var todoId = 1;
var _ = require("underscore");
app.use(bodyParser.json());
var todos = [
{
id:1,
description:'Have Lunch',
completed:false
},
{
id:2,
description:'Go to market',
completed:false
},
{
id:3,
description:'Go to park',
completed:true
}
];
app.use(express.static(__dirname+'/public'));
// GET /todos
app.get('/todos',function(req, res){
res.json(todos);
});
// GET /todos/:id
app.get('/todos/:id',function(req, res){
var todosId = parseInt(req.params.id,10);
var matchingTodo = _.findWhere(todos, {id:todosId});
// todos.forEach(function(todo){
// if(todo.id.toString() === todosId){
// matchingTodo = todo;
// }
// });
if(matchingTodo !== undefined){
res.json(matchingTodo);
}else{
console.log('Unable to find data for todo id:'+todosId);
res.status(404).send();
}
});
// POST /todos
app.post('/todos',function(req,res){
var body = _.pick(req.body,"description","completed");
if(_.isString(body.description)){
todoId = todos.length + 1;
body.id = todoId;
todos.push(body);
res.json(body);
}else{
res.status(404).send();
}
});
app.listen(PORT, function(){
console.log('Express server started...');
})