2016-04-11 49 views
3

我正在學習製作Todo應用程序。 在網站上,我學習是https://coderwall.com/p/4gzjqw/build-a-javascript-todo-app-with-express-jade-and-mongodbRoute.get()需要回調函數,但得到了「對象未定義」

我類型爲指令描述,

[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'); 
    } 
}; 

,我得到這個錯誤消息

Error: Route.get() requires callback functions but got a [object Undefined]

難道我在這裏錯過了什麼?

+0

下一步,它要求創建其他文件,main.js和jade模板,然後才能正常工作。我不知道會發生什麼 – jaykodeveloper

回答

5

在教程中,todo.all返回callback對象。這是router.get語法所必需的。

從文檔:

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.

你仍然需要定義你的todo文件callback對象的數組,因此您可以爲您的router訪問正確的callback對象。

您可以從您的教程,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') 
    } 
}; 
+0

謝謝你的好解釋!這是有點可以理解的 – jaykodeveloper

1

有用於獲得兩個途徑:

app.get('/', main.index); 
todoRouter.get('/',todo.all); 

錯誤:Route.get()需要回調函數,但得到[對象未定義]route.get沒有得到回調函數。正如您在todo.js文件中定義todo.all一樣,但無法找到main.index。 這就是爲什麼它在你稍後在教程中定義main.index文件後的原因。

+0

謝謝你的時間和精力。它幫助到我! – jaykodeveloper

0

確保

yourFile.js:

exports.yourFunction = function(a,b){ 
    //your code 
} 

比賽

app.js

var express = require('express'); 
var app = express(); 
var yourModule = require('yourFile'); 
app.get('/your_path', yourModule.yourFunction); 

對於我來說,我就遇到了這個問題,當複製粘貼模塊進入另一個模塊進行測試,需要改變出口。 xxxx位於文件頂部

相關問題