首页 > 解决方案 > NodeJS Express 和 EJS 使用 id 渲染路由

问题描述

我是否必须使用 id 才能在我的 ejs 文件中使用不同的对象?当我尝试使用与我的 json 对象不同的属性进行渲染时,我得到一个“未定义的错误”。

这是我的 JSON:

[{
    "id": 0,
    "TABLE_NAME": "t_Cards",
    "NUM_OF_ROWS": 33
},
{
    "id":1,
    "TABLE_NAME":"t_Users",
    "NUM_OF_ROWS": 44
},
{
    "id":2,
    "TABLE_NAME":"t_Date",
    "NUM_OF_ROWS": 44
}]

这是我的代码:

const express = require('express');
const app = express();
const dataTables = require('./routes/data/dataTables.json');
const tableRouter = express.Router();

app.set('view engine', 'ejs');
app.set('views', './views');
   
// This is going to render the index page. 
app.get('/', (req, res) => {
    res.render('index', {
        dataTables,
});

app.use('/dataDictionarys', tableRouter);

// I think the /:id might be part of the Express Framework? I could be wrong
tableRouter.route('/:id').get((req, res) => {
    const ID = req.params.id;
    res.render('./dataDictionarys/dataDictionary', {
        dataTable : dataTables[ID],
    })
});

console.log("app is listening");
app.listen(5000);

我必须使用id吗?当我尝试使用 TABLE_NAME 来识别我的对象并在 URL 中使用 TABLE_NAME 时,它显示 TABLE_NAME 未定义。id 只是 Express 或 ejs 框架的一部分吗?这是否意味着我的所有 json 对象都具有 id 属性是最佳实践?

标签: node.jsexpressejs

解决方案


推荐阅读