Route.get()需要回调函数但得到一个"未定义的对象"

jay*_*o03 23 node.js express

我正在学习制作Todo应用程序.在网站上,我正在学习的是https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodb

我输入的指令描述,

[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');
  }
};
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息

错误:Route.get()需要回调函数但得到[对象未定义]

我在这里错过了什么吗?

rof*_*ggo 19

在教程中,todo.all返回一个callback对象.这是router.get语法所必需的.

从文档:

router.METHOD(path,[callback,...] callback)

router.METHOD()方法在Express中提供路由功能,其中METHOD是HTTP方法之一,例如GET,PUT,POST等,小写.因此,实际的方法是router.get(),router.post(),router.put()等.

您仍然需要callbacktodo文件中定义对象数组,以便可以访问适当的callback对象router.

您可以在教程中看到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')
    }
};
Run Code Online (Sandbox Code Playgroud)


小智 12

有时你会错过下面的线。添加这个路由器就会明白这一点。

module.exports = router;
Run Code Online (Sandbox Code Playgroud)

  • 发生在我身上。我错误地输入了“module.export”而不是“module.exports” (2认同)

Dia*_*aBo 10

我得到了同样的错误。经过调试,我发现我从控制器导入到路由文件中的方法名称拼错了。请检查方法名称。

  • 先生,您是我的英雄! (3认同)

Niv*_*esh 7

获取途径有两种:

app.get('/', main.index);
todoRouter.get('/',todo.all);
Run Code Online (Sandbox Code Playgroud)

错误:Route.get() 需要回调函数,但得到一个 [object Undefined]route.get没有得到回调函数时抛出这个异常。正如你在 todo.js 文件中定义了 todo.all 一样,但是找不到 main.index。这就是为什么它会在您稍后在教程中定义 main.index 文件后起作用的原因。


Nic*_*ick 5

Make sure that

yourFile.js:

exports.yourFunction = function(a,b){
  //your code
}
Run Code Online (Sandbox Code Playgroud)

matches

app.js

var express = require('express');
var app = express();
var yourModule = require('yourFile');
app.get('/your_path', yourModule.yourFunction);
Run Code Online (Sandbox Code Playgroud)

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