Skip to content

Instantly share code, notes, and snippets.

@learosema
Last active April 8, 2020 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save learosema/603e473b876d974061a76b3e51ce9979 to your computer and use it in GitHub Desktop.
Save learosema/603e473b876d974061a76b3e51ce9979 to your computer and use it in GitHub Desktop.
Node Express Guestbook API

A little Guestbook API in node express :)

This is a little guestbook API. It uses a JSON file as a database. And for laziness, I used synchronous writes. Yes, this is bad practice.

npm i express body-parser
node server
const HOST = process.env.HOST || "0.0.0.0";
const PORT = process.env.PORT || 1337;
const DB_FILE = "guestbook.json";
const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
function getPosts() {
if (!fs.existsSync(DB_FILE)) {
return [];
} else {
const data = JSON.parse(fs.readFileSync(DB_FILE, "utf8"));
if (data instanceof Array) {
return data;
}
return [];
}
}
app.get("/api/guestbook", (req, res) => {
res.json(getPosts());
});
app.post("/api/guestbook", (req, res) => {
const post = {
name: req.body.name,
email: req.body.email,
title: req.body.title,
message: req.body.message,
date: new Date().toISOString(),
};
fs.writeFileSync(DB_FILE, JSON.stringify([post].concat(getPosts())), "utf8");
res.json({'ok': true});
});
app.listen(PORT, HOST, () =>
console.log(`Backend listening on http://${HOST}:${PORT}/`)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment