2016-05-17 55 views
0

我使用Express创建了一个Node.js项目,并在使用自定义路由时得到了此异常。Express&Node.js异常:500 TypeError:fn不是函数

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)

而且我通过

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

在我webhook.js申报app.js路线,

/* 
* GET Webhook. 
*/ 

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

但是,我用另一种方式来声明在应用程序的路径.js,就像

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

我没有得到那个ex ception。

有人知道为什么吗?

回答

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) { ... } 
}); 

这是无效的,因为快递想要一个函数参数,而不是一个对象。

相反,你要使用导出的模块对象的属性webhook

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

感谢罗伯特,它看起来像一个愚蠢的语法错误。但是您是否知道调试node.js的好方法,比如有一个突破点并查看本地变量的值? –

+0

@HaichenLiu你可以尝试['node-inspector'](https://github.com/node-inspector/node-inspector),这在我的经验中效果很好。 – robertklep