pragspri Ответов: 1

Typeerror: не удается прочитать свойство 'title' undefined in node.js


In shop.js controller file I rendered the product-details.ejs file and in that file I dynamically trying to retrieve the product.title description etc. when I try to execute it is throwing an error in product-detail.ejs file as title is not defined


shop.js контроллер

const Product=require('../models/product.js');


exports.getProducts=(req,res,next)=>{
    Product.fetchAll((products)=>{
        res.render('shop/product-list.ejs',{
            prods:products,
            pageTitle:'shop',
            path:'/'
        });

    });

};

exports.getProduct=(req,res,next)=>{
    const prodId=req.params.productId;
    Product.findById(prodId,product=>{
        res.render('shop/product-detail.ejs',{
            product:product,
            pageTitle: product.title,
            path:'/products'
        });
    });
};


exports.getIndex=(req,res,next)=>{
    Product.fetchAll((products)=>{
        res.render('shop/index.ejs',{
            prods:products,
            pageTitle:'index',
            path:'/'
        });

    });

};


exports.getCart=(req,res,next)=>{
    Product.fetchAll((products)=>{
        res.render('shop/cart.ejs',{
            prods:products,
            pageTitle:'cart',
            path:'/cart'
        });

    });

};

exports.getOrders=(req,res,next)=>{
    Product.fetchAll((products)=>{
        res.render('shop/order.ejs',{
            prods:products,
            pageTitle:'order',
            path:'/order'
        });

    });

};

exports.getCheckout=(req,res,next)=>{
    Product.fetchAll((products)=>{
        res.render('shop/checkout.ejs',{
            prods:products,
            pageTitle:'checkout',
            path:'/checkout'
        });

    });

};


шаблон файла с описанием товара.EJS по

<%- include('../includes/head.ejs') %>
    </head>

    <body>
        <%- include('../includes/navigation.ejs') %>
        <main class="centered">
            <h1><%= product.title %></h1>
            <hr>
            <div>
                <img src="<%= product.imageUrl %>" alt="<%= product.title %>">
            </div>
            <h2><%= product.price %></h2>
            <p><%= product.description %></p>
            <form action="/cart" method="post">
                <button class="btn" type="submit">Add to Cart</button>
            </form>
        </main>
        <%- include('../includes/end.ejs') %>


Что я уже пробовал:

In shop.js controller file I rendered the product-details.ejs file and in that file I dynamically trying to retrieve the product.title description etc. when I try to execute it is throwing an error in product-detail.ejs file as title is not defined

Richard MacCutchan

Сообщение на самом деле говорит вам, что ссылка на объект product не определено.

pragspri

Я определил объект продукта в shop.js файл exports.getProduct в контроллере во время рендеринга

1 Ответов

Рейтинг:
2

peter musembi

измените код в вашем models/product.js

 static findById(id, cb) {
   getProductsFromFile(products => {
     const product = products.find(p => p.id === id);
     cb(product === undefined ? "Product details" : product.title, product);
   });
}


путем замены
cb(product)

с
cb(product === undefined ? "Product details" : product.title, product);


затем отрегулируйте свой shop.js контроллер путем изменения
exports.getProduct=(req,res,next)=>{
    const prodId=req.params.productId;
    Product.findById(prodId,product=>{
        res.render('shop/product-detail.ejs',{
            product:product,
            pageTitle: product.title,
            path:'/products'
        });
    });
};

к
exports.getProduct = (req, res, next) => {
  const prodId = req.params.productId;
  Product.findById(prodId, (title,product) => {
     res.render('shop/product-detail', {
      product: product,
      pageTitle: title,
      path: '/products'
    });
  });
};