Created
May 15, 2019 19:10
-
-
Save picpoint/05f2f624ab3bb0eb3e16eb4eab997d5c to your computer and use it in GitHub Desktop.
simple server for work width json files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const http = require('http'); | |
const todos = require('./data/todos.json'); | |
const server = http.createServer(function (req, res) { | |
if (res.statusCode > 200) { | |
throw new Error('SERVER NOT STARTED', res.statusCode); | |
} | |
if (req.url == '/todos') { | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify(todos)); | |
} else if (req.url == '/todos/completed') { | |
const completed = todos.filter(todo => todo.completed); | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify(completed)); | |
} else if (req.url.match(/\/todos\/\d+/)) { | |
const id = parseInt(req.url.replace(/\D+/, '')); | |
const todo = todos.find(todo => todo.id === id); | |
if(!todo) { | |
res.writeHead(404, {'Content-Type': 'text/plain'}); | |
res.end('Not found'); | |
} else { | |
res.writeHead(200, {'Content-Type': 'application/json'}); | |
res.end(JSON.stringify(todo)); | |
} | |
} else { | |
res.writeHead(404, {'Content-Type': 'text/plain'}); | |
res.end('Not found'); | |
} | |
}); | |
server.listen(8080, function () { | |
console.log('server is starting ...'); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{ | |
"id": 1, | |
"title": "Изучить JS", | |
"completed": true | |
}, | |
{ | |
"id": 2, | |
"title": "Изучить Nodejs", | |
"completed": true | |
}, | |
{ | |
"id": 3, | |
"title": "Изучить Express", | |
"completed": false | |
}, | |
{ | |
"id": 4, | |
"title": "Написать приложение", | |
"completed": false | |
} | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment