You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EJS模板使用变量时触发ReferenceError问题求助

EJS模板无法识别路由传递的变量,触发ReferenceError问题

我正在开发一个微型博客项目,目标是让作者能将文章草稿存入数据库,之后可返回修改或发布。但目前遇到棘手问题:EJS模板无法识别对应.js文件中存储SQLite3表查询结果的变量,启动服务器访问对应路由时,EJS中使用的变量会触发ReferenceError。

初始代码

author.js

// Author Page
const express = require("express");
const router = express.Router();
const assert = require('assert');

/**
 * @desc retrieves draft articles
 */
router.get("/author-home", (req, res, next) => {

    //Use this pattern to retrieve data
    //NB. it's better NOT to use arrow functions for callbacks with this library
    global.db.all("SELECT * FROM draftArticles", function (err, rows) {
      if (err) {
        next(err); //send the error on to the error handler
      } else {
        res.json(rows);
      }
    });
});


/**
 * @desc Renders the author page
 */
router.get("/author", (req, res) => {
    res.render("author-home", data);
  });


module.exports = router;

author-home.ejs

<td><% data[0].article_title %> </td>
<td><% data[0].article_subtitle %> </td>

……(其他类似的文章属性插入代码)

修改后的尝试

发现data变量的作用域问题后,我修改了author.js代码:

// Author Page
const express = require("express");
const router = express.Router();
const assert = require('assert');

router.get('/author-home', (req, res, next) => {
    global.db.all('SELECT * FROM draftArticles', function (err, rows) {
      if (err) {
        console.log("No data found.")
        next(err); //send the error on to the error handler
        return;
      }
  
      res.render('author-home', { data: rows });
    });
});

module.exports = router;

但访问时EJS中访问data仍然触发ReferenceError。

我还尝试传递静态数据测试:

let dummyData = "This is test data";

router.get('/author-home', (req, res, next) => {
    res.render('author-home', { data: dummyData });
});

同样触发ReferenceError。

请问我哪里出错了?如果需要,我可以提供index.js的代码,感谢帮助!

内容的提问来源于stack exchange,提问作者Daniel Maxwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 14:05:14