-- server.js --

const express = require("express");
const bodyParser = require("body-parser");
const morgan = require("morgan");
const jsonfile = require("jsonfile");

const app = express();
const PORT = process.env.PORT || 3000;
const file = "./db/blogs.json";

app.set("view engine", "ejs");
app.listen(PORT);

app.use(bodyParser.json());
app.use(express.static("public"));
app.use(morgan("dev"));

app.get("/", async (req, res) => {
  try {
    const data = await jsonfile.readFile(file);
    res.render("index.ejs", { title: "Home", blogs: data });
  } catch (err) {
    console.log(err);
    res.status(500).render("sr.ejs", { title: "Server Error" });
  }
});

app.get("/new", (req, res) => {
  res.render("new.ejs", { title: "Create New Blog" });
});

app.post("/new-blog/", async (req, res) => {
  try {
    console.log(req.body);
    const blog = {
      title: req.body.title,
      author: req.body.author,
      content: req.body.content,
    };

    const data = await jsonfile.readFile(file);
    data.push(blog);
    await jsonfile.writeFile(file, data);
    console.log("file was written");
    res.redirect("/");
  } catch (err) {
    console.log(err);
    res.status(500).render("sr.ejs", { title: "Server Error" });
  }
});

app.get("/about", (req, res) => {
  res.render("about.ejs", { title: "About Us" });
});

app.use((req, res) => {
  res.render("nf.ejs", { title: "Page Not Found" });
});

process.on("uncaughtException", (err) => {
  console.log("UNCAUGHT ERROR:", err);
  process.exit(1);
});

-- new.ejs --

<!DOCTYPE html>
<html lang="en">
<%- include("./partials/head.ejs") %>
<body>
  <%- include("./partials/header.ejs") %>
  <main class="form-container">
    <form id="form" action="/new-blog/" method="post">
      <div>
        <label for="author">Author</label>
        <input
          id="author"
          name="author"
          type="text"
          placeholder="bobby8"
          required
          autocomplete="off"
        >
      </div>
      <div>
        <label for="title">Title</label>
        <input
          id="title"
          name="title"
          type="text"
          placeholder="My Favorite Movie"
          required
          autocomplete="off"
        >
      </div>
      <div>
        <label for="content">Content</label>
        <textarea
          id="content"
          name="content"
          type="text"
          placeholder="It has to be..."
          required
          autocomplete="off"
        ></textarea>
      </div>
      <button type="submit">Post Blog</button>
    </form>
  </main>
  <script src="/js/post-form.js"></script>
  <%- include("./partials/footer.ejs") %>
</body>
</html>

-- post-form.js --

const form = document.getElementById("form");

form.addEventListener("submit", async (e) => {
  const formData = new FormData(form);
  const blog = {};

  for (const [key, value] of formData.entries()) {
    blog[key] = value;
  }

  await fetch("/new-blog/", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(blog),
  });
});

-- blogs.json --

[{"title":"The Power of Positive Thinking","author":"AdventureSeeker87","content":"In a world filled with challenges and uncertainties, maintaining a positive mindset can make all the difference. The power of positive thinking lies in its ability to reshape our reality. When we focus on the good rather than the bad, we attract more positivity into our lives. Studies have shown that optimistic individuals are not only happier but also healthier. They have lower levels of stress and anxiety, and they are better equipped to handle life's curveballs. Cultivating a positive attitude is a choice we make every day. It requires practice and perseverance, but the rewards are immeasurable. So let's embrace the power of positive thinking and watch our lives transform for the better."},{"title":"Exploring the Wonders of Nature","author":"PositiveVibesOnly23","content":"Nature is a treasure trove of beauty and wonder, waiting to be explored. From the majestic mountains to the tranquil forests, there's something awe-inspiring about the great outdoors. Spending time in nature has been shown to have numerous benefits for our physical and mental well-being. Whether it's taking a hike in the woods or simply sitting by a babbling brook, connecting with nature can rejuvenate the soul. It reminds us of our place in the world and instills a sense of awe and gratitude. So let's lace up our boots, grab our backpacks, and embark on an adventure into the heart of nature. Who knows what wonders we'll discover along the way?"},{"title":"The Art of Productivity: Tips for Getting Things Done","author":"ProductivityNinja99","content":"In today's fast-paced world, being productive is more important than ever. But with so many distractions vying for our attention, staying focused can be a challenge. That's where the art of productivity comes in. By adopting the right habits and strategies, we can maximize our efficiency and accomplish more in less time. One key tip is to break tasks down into smaller, manageable chunks. This makes them less overwhelming and helps us stay motivated. Another helpful technique is to prioritize our tasks based on their importance and urgency. By tackling the most pressing tasks first, we can make steady progress toward our goals. And of course, it's essential to take breaks and recharge our batteries periodically. Whether it's going for a walk or practicing mindfulness, taking time for self-care is crucial for maintaining productivity in the long run. So let's harness the power of productivity and unleash our full potential."},{}]
tle":"wdwdw","author":"d","content":"dwdd"}]

Leave a comment




Comments