我使用 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/