-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
73 lines (61 loc) · 1.77 KB
/
index.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
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var logger = require('morgan');
var tasks = {
"1": { "id": '1', "text": "Read description of programming challenge" },
"2": { "id": "2", "text": "Implement awesome web app" },
"3": { "id": "3", "text": "Polish project" },
"9": { "id": "9", "text": "Send solution to LogMeIn" }
};
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'client/build')));
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/client/build/index.html'));
});
app.get('/api/tasks', function(req, res) {
res.json(tasks);
});
app.post('/api/tasks', function(req, res) {
console.log('POST a new Task', req.body);
if (!req.body || !req.body.id || !req.body.text) {
res.status(400).send('Invalid task format');
return;
}
if (tasks[req.body.id]) {
res.status(409).send('Conflict. Task already defined');
return;
}
tasks[req.body.id] = {
id: req.body.id,
text: req.body.text
};
res.status(204).send();
});
app.put('/api/tasks/:id', function(req, res) {
console.log('PUT a new Task', req.params.id, req.body);
if (!tasks[req.params.id]) {
res.status(404).send();
return;
}
tasks[req.params.id].text = req.body.text;
res.status(204).send();
});
app.delete('/api/tasks/:id', function(req, res) {
if (!tasks[req.params.id]) {
res.status(404).send();
return;
}
delete tasks[req.params.id];
res.status(204).send();
});
app.listen(3000, function () {
console.log('To-Do app listening on port 3000!');
});