首页 > 解决方案 > 传递对象引用错误

问题描述

最初我试图将对象:id 传递给它成功的 url,但之后当我尝试将对象传递给列表时,它开始显示 ReferenceError。

索引.ejs:

  <tr>
    <th class="text-center">AWB NO</th>
    <th class="text-center">Date</th>
    <th class="text-center">Supplier</th>
    <th class="text-center">Country</th>
  </tr>
</thead>
<tbody id="myTable">
  <tr>
    <td class="id"><a href="/dist" + AWB_NO>1687952</a></td>
    <td>06/06/2019</td>
    <td>Tropic Frozen</td>
    <td>Germany</td>
  </tr>

index.js:

router.get('/', function (req, res, next) {
    connection.query('SELECT * FROM orders', function (err, rows) {

        if (err) {
            req.flash('error', err);
            res.render('index', { page_title: "index - Node.js", data: '' });
        } else {

            res.render('index', { page_title: "index - Node.js", data: rows });

        }

    })
});

dist.ejs:

<li class="list-inline-item">AWB Number:<%= AWB_NO %></li>//尝试传递对象

dist.js:

router.get('/', function (req, res, next) {

    connection.query('SELECT * FROM deliveries', function (err, rows) {

        if (err) {
            req.flash('error', err);
            res.render('dist', { page_title: "dist - Node.js", data: '' });
        } else {

            res.render('dist', { page_title: "dist - Node.js", data: rows });

        }

    })
});

router.get('/:awb', function (req, res) {
    res.render('dist', {
     AWB_NO: req.params.awb
    })
});

错误:

ReferenceError: E:\Dev\admeghbalim\YinSeafood\YinSeafood\expressfirst\views\dist.ejs:20
    18|             <h3>Distributor information</h3><br>&nbsp;
    19|             <ul class="list-inline">
 >> 20|                 <li class="list-inline-item">AWB Number:<%= AWB_NO %></li> &nbsp;
    21|                 <li class="list-inline-item">Country:</li>&nbsp;
    22|                 <li class="list-inline-item">Date:</li>&nbsp;
    23|                 <li class="list-inline-item">Sender:</li>&nbsp;

AWB_NO is not defined

标签: javascriptnode.jsexpressejs

解决方案


您可以更改如下:

索引.ejs

    <tr>
    <th class="text-center">AWB NO</th>
    <th class="text-center">Date</th>
    <th class="text-center">Supplier</th>
    <th class="text-center">Country</th>
  </tr>
</thead>
<tbody id="myTable">
  <tr>
    <td class="id"><a href="/dist/<%= AWB_NO %>">1687952</a></td>
    <td>06/06/2019</td>
    <td>Tropic Frozen</td>
    <td>Germany</td>
  </tr>

在 index.js 中,我假设您传递了 AWB_NO 的值。假设您有任何数组或对象,您可以使用 for 循环进行迭代并像数组 ['AWB_NO'] 一样编写。它取决于您如何在渲染函数中传递值。更新了 dist.js:

  router.get('/dist/:awb',  function (req, res) {
        res.render('dist', {
            AWB_NO: req.params.awb
        })
});

dist.ejs:

<li class="list-inline-item">AWB Number:<%= AWB_NO %></li>

我希望你能解决问题。


推荐阅读