javascript - Express 和 Node.js 异常 : 500 TypeError: fn is not a function

标签 javascript node.js express

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

500 TypeError: fn is not a function at callbacks (/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:272:11) at param (/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:246:11) at pass (/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:253:5) at Router._dispatch (/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:280:5) at Object.Router.middleware [as handle] (/WallaceBot/WallaceBot/node_modules/express/lib/router/index.js:45:10) at next (/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/http.js:204:15) at Object.methodOverride [as handle] (/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/middleware/methodOverride.js:35:5) at next (/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/http.js:204:15) at Object.bodyParser [as handle] (/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:88:61) at next (/WallaceBot/WallaceBot/node_modules/express/node_modules/connect/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' })
});

我没有得到这个异常(exception)。

有人知道为什么吗?

最佳答案

var webhook 看起来像这样:

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

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

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

这是无效的,因为 Express 需要一个函数参数,而不是一个对象。

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

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

关于javascript - Express 和 Node.js 异常 : 500 TypeError: fn is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37282397/

相关文章:

javascript - redux 形式错误 : Element type is invalid: expected a string or function

javascript - 如何使用进度更新呈现的 Jade 页面?

node.js - 在 Node.js 中扩展原生 JS 对象?

parsing - 如何在 express.js Jade 模板中呈现 markdown?

javascript - 有没有一种方法可以复制几乎整个结构而不损坏源对象?

javascript - ubuntu pm2命令运行node-express站点

javascript - rails 6.1 : Webpacker can't find application. js

javascript - karma : Cannot find module in relative path

javascript - Node.js Express - app.all ("*", func) 在访问根域时不会被调用

node.js - Express.js session 在服务器重新启动时重置