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

Node/Express+Pug项目中为何不能分开实现函数定义与导出?

错误原因

你遇到的Route.get() requires a callback function but got a [object Undefined]报错,核心是导出语句不符合CommonJS规范,没有完成赋值操作:

  • 你写的exports.index;是属性读取语句,没有任何赋值行为,相当于只是访问了exports对象上的index属性,没有给这个属性关联任何值,此时exports.index默认值就是undefined。
  • 你已经在前面定义好了名为index的路由处理函数,只需要把这个函数赋值给exports.index即可完成导出。
修正方案

把控制器文件的最后一行导出语句修改为赋值形式即可:

// 原有函数定义不变
function index(req, res) {
    Livro.countDocuments({}, function(err, results){
        if (err){
            res.render('livrariaIndex2', {title: 'Livraria JBM Home', count: 'Erro!!!!'});        
        } else {
            res.render('livrariaIndex2', {title: 'Livraria JBM Home', count: results});
        }
    })
}

// 修正后的导出语句:把定义好的index函数赋值给exports的index属性
exports.index = index;
补充说明

你之前了解的直接定义导出的写法也是可行的,本质和分开定义再赋值的逻辑完全一致,都是给exports.index赋值函数:

exports.index = function(req, res) {
  // 路由处理逻辑
}

内容的提问来源于stack exchange,提问作者Jorge Barbi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 10:06:03