Node-Crush-Course(11~12)

➰ MVC

1. 📝Create 📃 Detail.ejs

<!DOCTYPE html>
<html lang="en">
<%- include("../partials/head.ejs") %> 
<body>
    <%- include("../partials/nav.ejs") %> 

    <div class="details content">
        <h2><%= blog.title %> </h2>
        <div class="content">
            <p><%= blog.body %> </p>
        </div>
        <a data-doc="<%= blog._id %>" class="delete">
            <img src="/trashcan.svg" alt="delete icon">
        </a>
        <!-- special attribute basically add our own custom attributes and we can call it, Store blog._id in data-doc, when we click a tag can grab this data-->
    </div>

    <%- include("../partials/footer.ejs") %> 

    <script>
        const trashcan = document.querySelector('a.delete');
        trashcan.addEventListener('click', (e) => {
            const endpoint = `/blogs/${trashcan.dataset.doc}`;
            fetch(endpoint, {
                method: "DELETE"
            })
            .then(response => response.json())
            .then(data => window.location.href = data.redirect)
            .catch(err => console.log(err));
        });
    </script>
</body>
</html>

2. 🔨Modify 📃 app.js

const express = require("express");
const morgan = require("morgan");
const mongoose = require("mongoose");
const app = express();
const blogRoutes = require("./routes/blogRoutes");

// connet to MongoDB
const dbURI =
  "";
mongoose
  .connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then((result) => app.listen(3000)) // db 연결 후 listen
  .catch((err) => console.log(err));
// Mongoose to connect and interact with the database like prisma?
// npm install mongoose
app.set("view engine", "ejs");

app.use(express.static("public"));
app.use(express.urlencoded({ extended: true })); // middleware that helps handling POST, URL request => Object request
app.use(morgan("dev"));

// routes
app.get("/", (req, res) => {
  res.redirect("/blogs");
});

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

//blog routes
app.use("/blogs", blogRoutes);

app.use((req, res) => {
  res.status(404).render("404", { title: "404" });
});

3. 📝Create 📃 blogRoutes.js

const express = require("express");
const blogController = require("../controllers/blogController");
const router = express.Router();

router.get("/", blogController.blog_index);

router.post("/", blogController.blog_create_post);

router.get("/create", blogController.blog_create_get);

router.get("/:id", blogController.blog_details);

router.delete("/:id", blogController.blog_delete);

module.exports = router;

4. 📝Create 📃 blogController.js

// blog_index : Get all the blogs and inject those into the index view
// blog_details : Get single blog
// blog_create_get : Send back the actual form, get request
// blog_create_post : Add a new blog and
// blog_delete : Delete a blog
const Blog = require("../models/blog");

const blog_index = (req, res) => {
  Blog.find()
    .sort({ createdAt: -1 }) //descending order
    .then((result) => {
      res.render("blogs/index", { title: "All Blogs", blogs: result });
    })
    .catch((err) => console.log(err));
};

const blog_details = (req, res) => {
  const id = req.params.id;
  Blog.findById(id)
    .then((result) => {
      res.render("detail", { blog: result, title: "Blog Details" });
    })
    .catch((err) => {
      res.render("404", { title: "Blog not found" });
    });
};

const blog_create_get = (req, res) => {
  res.render("blogs/create", { title: "Create a new Blog" });
};

const blog_create_post = (req, res) => {
  const blog = new Blog(req.body);
  blog.save().then((result) => {
    res.redirect("/blogs");
  });
};

const blog_delete = (req, res) => {
  const id = req.params.id;
  Blog.findByIdAndDelete(id)
    .then((result) => {
      res.json({ redirect: "/blogs" });
    })
    .catch((err) => {
      console.log(err);
    });
};

module.exports = {
  blog_index,
  blog_details,
  blog_create_get,
  blog_create_post,
  blog_delete,
};

5. 🔨Modify 📃 index.ejs

<!DOCTYPE html>
<html lang="en">
    <%- include('../partials/head.ejs') %>
<body>

    <%- include('../partials/nav.ejs') %> 

    <div class="blogs content">
        <h2>All Blogs</h2>

        <% if(blogs.length > 0)  { %>
            <% blogs.forEach(blog => { %>
                <div class="blog_wrapper">
                    <a class="single" href="/blogs/<%= blog._id %>">
                        <h3 class="title"><%= blog.title %> </h3>
                        <p class="snippet"><%= blog.snippet %> </p>
                    </a>
                </div>
            <% }) %> 
        <% } else { %> 
            <p>There are no blogs to display...</p>
        <% } %> 
    </div>
    <%- include('../partials/footer.ejs') %>
</body>
</html>

좋은 웹페이지 즐겨찾기