2016-02-16 36 views
0

我嘗試在node.js上創建一個API,按照一些舊教程修復一些小問題,但我在這裏停留了兩個小時,我只想獲得所有從mongodbLab的數據,保持saingNode.js APT無法從mongodbLab獲取數據

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

請幫助

這是app.js

var express = require('express'), 
songs = require('./routes/route'); 

var app = express(); 
app.get('/', function (req, res) { 
res.send('Hello World!'); 
}); 

app.listen(3000, function() { 
console.log('Example app listening on port 3000!'); 
}); 


app.get('/songs',songs.findAll()); 

這是路線

var mongoose = require('mongoose'); 
var mongo = require('mongodb'); 
var uri = "mongodb://user:[email protected]:61365/aweitest"; 
mongoose.connect(uri); 

// we're connected! 
var db = mongoose.connection; 

db.on('error', console.error.bind(console, 'connection errrrrrrrror:')); 

db.once('open', function() { 
console.log("mongodb is connected!!"); 
}); 

exports.findAll = function(req, res) { 
db.collection('songs', function(err, collection) { 
collection.find().toArray(function(err, items) { 
    res.send(items); 
}); 
}); 
}; 

這是錯誤

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" 
"C:\Program Files\nodejs\node.exe" app.js 
c:\Users\awei\node_modules\express\lib\router\route.js:196 
    throw new Error(msg); 
    ^

Error: Route.get() requires callback functions but got a [object Undefined] 
at Route.(anonymous function) [as get] (c:\Users\awei\node_modules\express\lib\router\route.js:196:15) 
at EventEmitter.app.(anonymous function) [as get] (c:\Users\awei\node_modules\express\lib\application.js:481:19) 
at Object.<anonymous> (c:\Users\awei\WebstormProjects\untitled\app.js:16:5) 
at Module._compile (module.js:413:34) 
at Object.Module._extensions..js (module.js:422:10) 
at Module.load (module.js:357:32) 
at Function.Module._load (module.js:314:12) 
at Function.Module.runMain (module.js:447:10) 
at startup (node.js:140:18) 
at node.js:1001:3 

回答

1

你行;

app.get('/songs',songs.findAll()); 

...呼籲立即findAll並設置調用的返回值(在這種情況下是Undefined因爲函數沒有返回值)

你想要什麼路線;

app.get('/songs',songs.findAll); 

...它設置執行獲取時調用實際函數的路徑。

+0

你是對的!現在沒有錯誤! 但是當我輸入本地主機:3000 /歌曲 它應該打印出所有的數據吧? 或者我需要編寫一些代碼來打印出來? –

+0

@AweiHsue由於'res.send(items)',你應該得到瀏覽器中的所有數據,它應該發送響應中的所有項目。 –

+1

謝謝!現在它沒有發佈任何內容,似乎在exports.findAll = function(req,res){...}處有一些問題,正在尋找doc來解決它:D –