const express = require("express");
const shopController = require("../controllers/shop");
const router = express.Router();
...
router.get("/products/:productId", shopController.getProduct); // #1
...
module.exports = router;
const Product = require("../models/product");
const Cart = require("../models/cart");
...
exports.getProduct = (req, res, next) => {
const prodId = req.params.productId;
Product.findById(prodId, (product) => {
res.render("shop/product-detail", {
product: product,
pageTitle: product.title,
path: "/products",
});
});
};
...
productId에 액세스할 수 있는 이유는 shop.js 라우트 파일에서 콜론 후에 오는 이름으로 productId를 사용했기 때문이다. 콜론 다음에 사용하는 이름이 params 객체에서 데이터를 추출할 사용하는 이름이 된다.
<% if (prods.length > 0) { %>
<div class="grid">
<% for (let product of prods) { %>
<article class="card product-item">
<header class="card__header">
<h1 class="product__title">
<%= product.title %>
</h1>
</header>
<div class="card__image">
<img src="<%= product.imageUrl %>" alt="<%= product.title %>">
</div>
<div class="card__content">
<h2 class="product__price">$
<%= product.price %>
</h2>
<p class="product__description">
<%= product.description %>
</p>
</div>
<div class="card__actions">
<a href="/products/<%= product.id%>" class="btn">Details</a>
<%- include('../includes/add-to-cart.ejs', {product: product})%>
</div>
</article>
<% } %>
</div>
<% } else { %>
<h1>No Products Found!</h1>
<% } %>
</main>