node.js Route.get() 需要回调函数,但得到了一个“对象未定义”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36558909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Route.get() requires callback functions but got a "object Undefined"
提问by jayko03
I am learning making Todo app. On the website, I am studying is https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb
我正在学习制作 Todo 应用程序。在网站上,我正在研究的是https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb
I typed as instruction describes,
我按照说明输入,
[app.js]
var main = require('./routes/main');
var todo = require('./routes/todo');
var todoRouter = express.Router();
app.use('/todos', todoRouter);
app.get('/', main.index);
todoRouter.get('/',todo.all);
todoRouter.post('/create', todo.create);
todoRouter.post('/destroy/:id', todo.destroy);
todoRouter.post('/edit/:id', todo.edit);
[/routes/todo.js]
module.exports ={
all: function(req, res){
res.send('All todos');
},
viewOne: function(req, res){
console.log('Viewing '+req.params.id);
},
create: function(req, res){
console.log('Todo created');
},
destroy: function(req, res){
console.log('Todo deleted');
},
edit: function(req, res){
console.log('Todo '+req.params.id+' updated');
}
};
and I got this error message
我收到了这个错误信息
Error: Route.get() requires callback functions but got a [object Undefined]
错误:Route.get() 需要回调函数但得到一个 [object Undefined]
Did I miss something here?
我在这里错过了什么吗?
采纳答案by roflmyeggo
In the tutorial the todo.allreturns a callbackobject. This is required for the router.getsyntax.
在教程中todo.all返回一个callback对象。这是router.get语法所必需的。
From the documentation:
从文档:
router.METHOD(path, [callback, ...] callback)
The router.METHOD() methods provide the routing functionality in Express, where METHOD is one of the HTTP methods, such as GET, PUT, POST, and so on, in lowercase. Thus, the actual methods are router.get(), router.post(), router.put(), and so on.
router.METHOD(path, [callback, ...] callback)
router.METHOD() 方法在 Express 中提供路由功能,其中 METHOD 是 HTTP 方法之一,例如小写的 GET、PUT、POST 等。因此,实际的方法是 router.get()、router.post()、router.put() 等等。
You still need to define the array of callbackobjects in your todofiles so you can access the proper callbackobject for your router.
您仍然需要callback在todo文件中定义对象数组,以便您可以访问callback适合您的router.
You can see from your tutorial that todo.jscontains the array of callbackobjects (this is what you are accessing when you write todo.all):
您可以从todo.js包含callback对象数组的教程中看到(这是您编写时正在访问的内容todo.all):
module.exports = {
all: function(req, res){
res.send('All todos')
},
viewOne: function(req, res){
console.log('Viewing ' + req.params.id);
},
create: function(req, res){
console.log('Todo created')
},
destroy: function(req, res){
console.log('Todo deleted')
},
edit: function(req, res){
console.log('Todo ' + req.params.id + ' updated')
}
};
回答by Nivesh
There are two routes for get:
获取途径有两种:
app.get('/', main.index);
todoRouter.get('/',todo.all);
Error: Route.get() requires callback functions but got a [object Undefined]This exception is thrown when route.getdoes not get a callback function. As you have defined todo.all in todo.js file, but it is unable to find main.index.
That's why it works once you define main.index file later on in the tutorial.
错误:Route.get() 需要回调函数,但得到一个 [object Undefined]当route.get没有得到回调函数时抛出这个异常。正如你在 todo.js 文件中定义了 todo.all 一样,但是找不到 main.index。这就是为什么它会在您稍后在教程中定义 main.index 文件后起作用的原因。
回答by Nick
Make sure that
确保
yourFile.js:
你的文件.js:
exports.yourFunction = function(a,b){
//your code
}
matches
火柴
app.js
应用程序.js
var express = require('express');
var app = express();
var yourModule = require('yourFile');
app.get('/your_path', yourModule.yourFunction);
For me, I ran into this issue when copy pasting a module into another module for testing, needed to change the exports. xxxx at the top of the file
对我来说,我在将一个模块复制粘贴到另一个模块进行测试时遇到了这个问题,需要更改导出。文件顶部的 xxxx
回答by Yogesh Shetty
Some time you miss below line. add this router will understand this.
有时你会错过下面的线。添加此路由器将了解这一点。
module.exports = router;
回答by DiaMaBo
I got the same error. After debugging, I found that I misspelled the method name that I imported from the controller into the route file. Please check the method name.
我得到了同样的错误。经过调试,我发现我从控制器导入到路由文件中的方法名称拼错了。请检查方法名称。
回答by Jonathan Mendoza
I had the same error. The problem was in the export and import of the modules.
我有同样的错误。问题在于模块的导出和导入。
Example of my solution:
我的解决方案示例:
Controller (File: posts.js)
控制器(文件:posts.js)
exports.getPosts = (req, res) => {
res.json({
posts: [
{ tittle: 'First posts' },
{ tittle: 'Second posts' },
]
});
};
Router (File: posts.js)
路由器(文件:posts.js)
const express = require('express');
const { getPosts } = require('../controllers/posts');
const routerPosts = express.Router();
routerPosts.get('/', getPosts);
exports.routerPosts = routerPosts;
Main (File: app.js)
主要(文件:app.js)
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
const { routerPosts } = require('./routes/posts');
const app = express();
const port = process.env.PORT || 3000;
dotenv.config();
// Middleware
app.use(morgan('dev'));
app.use('/', routerPosts);
app.listen(port, () => {
console.log(`A NodeJS API is listining on port: ${port}`);
});
Running the application (chrome output)
运行应用程序(chrome 输出)
// 20200409002022
// http://localhost:3000/
{
"posts": [
{
"tittle": "First posts"
},
{
"tittle": "Second posts"
}
]
}
Console Log
控制台日志
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Basic-Node-API$ npm run dev
> [email protected] dev /home/jmendoza/IdeaProjects/NodeJS-API-Course/Basic-Node-API
> nodemon app.js
[nodemon] 2.0.3
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 304 5.093 ms - -
GET / 304 0.714 ms - -
GET / 304 0.653 ms - -
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
A NodeJS API is listining on port: 3000
GET / 200 4.427 ms - 62
GET / 304 0.783 ms - -
GET / 304 0.642 ms - -
Node Version
节点版本
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ node -v
v13.12.0
NPM Version
新版本
jmendoza@jmendoza-ThinkPad-T420:~/IdeaProjects/NodeJS-API-Course/Node-API$ npm -v
6.14.4
回答by Hyman.the.ripper
What happened to me is I was exporting a function like this:
发生在我身上的是我正在导出这样的函数:
module.exports = () => {
const method = async (req, res) => {
}
return {
method
}
}
but I was calling it like this:
但我是这样称呼它的:
const main = require('./module');
instead
反而
const main = require('./module')();
回答by shr_kuldeep
This thing also happened with my code, but somehow I solved my problem. I checked my routes folder (where my all endpoints are their). I would recommend you check your routes folder file and check whether you forgot to add your particular router link.
这件事也发生在我的代码上,但不知何故我解决了我的问题。我检查了我的路由文件夹(我的所有端点都是他们的)。我建议您检查您的路由文件夹文件,并检查您是否忘记添加特定的路由器链接。
回答by Raghavendra M
In my case I was trying to 'get' from express app. Instead I had to do SET.
就我而言,我试图从快递应用程序中“获取”。相反,我不得不做 SET。
app.set('view engine','pug');
回答by Raghavendra M
node js and express 4 use this sequences
node js 和 express 4 使用这个序列
express = require('express');
var router = express.Router();
module.exports = router;
last line returns this type of error
最后一行返回这种类型的错误

