Cleaned up server.js a bit

This commit is contained in:
Thomas Wade 2018-10-29 18:33:32 +10:30
parent f860fceeb6
commit 99dcd64820

View File

@ -13,17 +13,20 @@ app.use(express.json()); // Parse JSON in requests
// }); // });
// Root route, respond with with index.html // Root route, respond with with index.html
app.get("/", function(req, res) { app.get("/", function(req, res)
{
res.sendFile("./index.html"); res.sendFile("./index.html");
}); });
// Posts route, return posts.json // Posts route, return posts.json
app.get("/posts", function(req, res) { app.get("/posts", function(req, res)
{
res.json(JSON.parse(fs.readFileSync('./data/posts.json'))); res.json(JSON.parse(fs.readFileSync('./data/posts.json')));
}); });
// Posts route, digest received post // Posts route, digest received post
app.post("/posts", function(req, res) { app.post("/posts", function(req, res)
{
var postsFile = fs.readFileSync('./data/posts.json'); var postsFile = fs.readFileSync('./data/posts.json');
var posts = JSON.parse(postsFile); var posts = JSON.parse(postsFile);
@ -38,7 +41,8 @@ app.post("/posts", function(req, res) {
return; return;
} }
fs.writeFile('./data/posts.json', JSON.stringify(posts), (e) => { fs.writeFile('./data/posts.json', JSON.stringify(posts), (e) =>
{
if (e) if (e)
{ {
res.sendStatus(500); res.sendStatus(500);
@ -50,10 +54,12 @@ app.post("/posts", function(req, res) {
}); });
// Start listening // Start listening
app.listen(8080, function (){ app.listen(8080, function()
{
console.log("Listening on port 8080"); console.log("Listening on port 8080");
}); });
// Validates a post object conforms to the standard we're expecting
function validatePost(post) function validatePost(post)
{ {
try try