-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
52 lines (39 loc) · 904 Bytes
/
Copy pathserver.js
File metadata and controls
52 lines (39 loc) · 904 Bytes
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
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var PORT = process.env.PORT || 3000;
var todos = [];
var todoNextId =1;
app.use(bodyParser.json());
app.get('/', function(req, res){
res.send('Todo API Root');
});
//Get /todos
app.get('/todos', function (req,res) {
res.json(todos);
});
app.get('/todos/:id',function(req, res){
var todoID = parseInt(req.params.id, 10);
var matchedTodo;
todos.forEach(function(todo) {
if(todoID === todo.id){
matchedTodo = todo;
}
});
if(matchedTodo){
res.json(matchedTodo);
} else{
res.status(404).send();
}
// Iterate of todos array, find the match.
});
//Post request /todos
app.post('/todos',function(req, res){
var body =req.body;
body.id = todoNextId++;
todos.push(body);
res.json(body);
});
app.listen(PORT, function(){
console.log('Express listening on port' + PORT + '!');
});