0

我的 nodejs 项目有一个非常奇怪的问题。该项目是一个带有快递和车把的在线商店,它连接了一个 mongo 数据库。在路由器部分我有这个代码:

router.get('/item/:item', function (req, res, next) {
var actItem = {};
Item.find().findOne({ '_id': req.params.item }, function (err, item) {
    actItem.name = item.item_name;
    actItem.price = item.price;
    actItem.description = item.description;
    actItem.imageLink = item.imageLink;

});
res.render('pages/shop/item-view', { title: 'Express', item: actItem });

});

它在数据库的 URL 中查找项目 ID,并返回传递要显示的数据的视图。它工作得很好,但是在视图中我有这个代码:

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
    <div class="carousel-item active">
        <img class="d-block w-100" src="{{item.imageLink}}" alt="First slide">
    </div>
    <div class="carousel-item">
        <img class="d-block w-100" src="" alt="Second slide">
    </div>
    <div class="carousel-item">
        <img class="d-block w-100" src="" alt="Third slide">
    </div>
</div>
<a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
</a>

它也可以正常工作!但问题来了。每当我在任何 src 属性中添加三个点时,它都会崩溃。更奇怪的是,即使我在 chrome 中渲染后编辑 html 文档并添加它们,它也会崩溃,如下所示:

<img class="d-block w-100" src="..." alt="Second slide">

崩溃的错误是这样的:

actItem.name = item.item_name;
                    ^
TypeError: Cannot read property 'item_name' of undefined

关于如何解决这个问题以及为什么会发生的任何想法?

解决方案

我设法通过在做任何事情之前检查项目来解决这个问题。

if (item) {
  actItem.name = item.item_name;
  actItem.price = item.price;
  actItem.description = item.description;
  actItem.imageLink = item.imageLink;
}

发生这种情况是因为当我使用 ... 浏览器发出请求 /item/... 来获取图像时, req.params.item 的值变为 ... 并且在数据库中没有 _id = .. 的条目... 所以项目值很好是未定义的

4

1 回答 1

2

findOne是一个异步函数,所以res.render 在它里面调用,并检查 item 是否不为空:

router.get('/item/:item', function (req, res, next) {
var actItem = {};

    Item.find().findOne({ '_id': req.params.item }, function (err, item) {
        if(item){
            actItem.name = item.item_name;
            actItem.price = item.price;
            actItem.description = item.description;
            actItem.imageLink = item.imageLink;
            res.render('pages/shop/item-view', { title: 'Express', item: actItem 
         }
         else{
            res.render('pages/shop/item-view', { title: 'Express', item: 'defaultValue'});
         }

    });
 });
于 2017-11-05T12:54:24.760 回答