首页 文章

Express&Node.js异常:500 TypeError:fn不是函数

提问于
浏览
0

我使用Express创建了一个Node.js项目,并在使用自定义路由时遇到此异常 .

500 TypeError:fn不是param上的回调函数(/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:272:11)(/ WallaceBot / WallaceBot / node_modules / express / lib / router / index .js:246:11)在Router._dispatch传递(/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:253:5)(/ WallaceBot / WallaceBot / node_modules / express / lib / router / index .js:280:5)在Object.Router.middleware [作为句柄](/ WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:45:10)下一步(/ WallaceBot / WallaceBot / node_modules / express) /node_modules/connect/lib/http.js:204:15)在Object.methodOverride [as handle](/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:35:5)at at在Object.bodyParser [作为句柄]的下一个(/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/http.js:204:15)(/ WallaceBot / WallaceBot / node_modules / express / node_modules / connect / lib / middleware /bodyParser.js:88:61)下一个(/ WallaceBot / WallaceBot / node_modules /表达/ node_modules /连接/ LIB / http.js:204:15)

我在app.js中声明了路由

var webhook = require('./routes/webhook.js');
app.get('/', routes.index);
app.get('/webhook', webhook);

在我的webhook.js中,

/*
 * GET Webhook.
 */

exports.webhook = function(req, res){
  res.render('index', { title: 'Webhook' })
};

但是,我使用另一种方式在app.js中声明路由,比如

app.get('/webhook', function(req, res){
  res.render('index', { title: 'Webhook' })
});

我没有得到那个例外 .

有人知道为什么吗?

2 回答

  • 1

    作为另一个答案的替代解决方案,您可以将webhook.js文件更改为如下所示:

    /*
     * GET Webhook.
     */
    
    exports = module.exports = function(req, res){
      res.render('index', { title: 'Webhook' })
    };
    
  • 3

    var webhook 看起来像这样:

    {
      "webhook" : function(req, res) { ... }
    }
    

    所以您的路由处理程序设置如下所示:

    app.get('/webhook', {
      "webhook" : function(req, res) { ... }
    });
    

    哪个是无效的,因为Express想要一个函数参数,而不是一个对象 .

    相反,您希望使用导出的模块对象的 webhook 属性:

    var webhook = require('./routes/webhook.js').webhook;
    

相关问题