快速路由:.get() 需要回调函数但得到一个 [object Object] [英] Express routes: .get() requires callback functions but got a [object Object]
问题描述
好的,这对有人来说应该很容易指出.
Ok, this should be easy for somebody to point out.
我检查了其他类似的问题,但没有任何帮助.
I checked the other similar questions and none helped.
我正在尝试将所有路由移动到一个单独的 routes.js
文件中.其中我有:
I'm trying to move all my routes to a separate routes.js
file. In it I have:
module.exports = function (app) {
var user = {
list : require('./routes/user.js')
}
, index = {
index : require('./routes/index.js')
}
app.get('/', function(request, response){
response.send('You made it to the home page.')
});
app.get('/users', user.list);
}
在我的 app.js
文件中,我有这个:
And in my app.js
file I have this:
var register_routes = require('./routes.js')
register_routes(app)
我的索引路由工作正常,但它在 app.get('/users', user.list);
上出现错误:
My index route works fine, but it kicks back on app.get('/users', user.list);
with this error:
.get() 需要回调函数,但得到了一个 [object Object]
.get() requires callback functions but got a [object Object]
这是一个开箱即用的快递应用程序,因此无需过多描述.
This is an out of the box express app so theres not too much to describe.
谢谢.
根据请求,这是 ./routes/user.js
中的内容:
Per request, here is what is in ./routes/user.js
:
exports.list = function(req, res){
res.send("respond with a resource");
};
推荐答案
您使用键 list
导出一个对象,该键将您的函数作为值.
You export an object with the key list
having the your function as value.
因此要访问您的功能,您需要执行此操作 require('./routes/user.js').list
So to access your function you would need to do this require('./routes/user.js').list
或者使用您的代码user.list.list
.
要解决这个问题,您有两种可能性.
To solve this you have two possibilities.
要么写:
var user = {
list : require('./routes/user.js').list
}
或者:
module.exports = function(req, res){
res.send("respond with a resource");
};
编辑
如果你的 routes/user.js
以后可能看起来像这样:
If your routes/user.js
will probably later look like this:
module.exports.list = function(req, res){
res.send("respond with a resource");
};
module.exports.delete = function(req, res){
res.send("delete user");
};
如果是,那么你可以在你的 routes.js
中这样写:
If yes then you can just write it that way in your routes.js
:
var user = require('./routes/user.js');
这篇关于快速路由:.get() 需要回调函数但得到一个 [object Object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!