2015-12-23 83 views
0

我正在嘗試使用Node.js,Express和MongoDB創建Rest API。我目前在我的本地主機上運行:3000。當我嘗試重新啓動並運行服務器時,我正在使用路由http://localhost:3000/drinks無法使用Express NodeJS和MongoDB從API檢索數據,正在加載

我使用Postman發送HTTP請求。 https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en

嘗試發送上述路由時,它不檢索任何信息。它只是繼續加載。

這是我第一次創建一個REST API,我不確定它爲什麼不檢索數據。下面是我的代碼。提前致謝!

server.js

var express = require('express'), 
    drink = require('./routes/drinks'); 

var app = express(); 

app.configure(function() { 
     app.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */ 
     app.use(express.bodyParser()); 
    }); 

app.get('/drinks', drink.findAll); 
app.get('/drinks/:id', drink.findById);                  

app.listen(3000); 
console.log('Listening on port 3000...'); 

drinks.js

var mongo = require('mongodb'); 

var Server = mongo.Server, 
    Db = mongo.Db, 
    BSON = mongo.BSONPure; 

var server = new Server('localhost', 27017, {auto_reconnect: true}); 
db = new Db('drinkdb', server); 

db.open(function(err, db) { 
     if(!err) { 
      console.log("Connected to 'drinkdb' database"); 
      db.collection('drinks', {strict:true}, function(err, collection) { 
        if (err) { 
         console.log("The 'drinks' collection doesn't exist. Creating it with sample data..."); 
         populateDB(); 
        } 
       }); 
     } 
    }); 

exports.findById = function(req, res) { 
    var id = req.params.id; 
    console.log('Retrieving drink: ' + id); 
    db.collection('drinks', function(err, collection) { 
      collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) { 
        res.send(item); 
       }); 
     }); 
}; 

exports.findAll = function(req, res) { 
    db.collection('drinks', function(err, collection) { 
      collection.find().toArray(function(err, drinks) { 
        res.send(drinks); 
       }); 
     }); 
}; 
/*---------------------------------------------------------------------------------------------------------------*/ 
// Populate database with sample data -- Only used once: the first time the application is started.     
// You'd typically not find this code in a real-life app, since the database would already exist.      
var populateDB = function() { 

    var drinks = [ 
    { 
      id: "1", 
      name: "Margarita", 
      ingredients: ["Tequila","Lime juice","Triple Sec","Lime","Salt","Ice"], 
      measurements: ["2 oz","1 oz","1 oz","1","optional","optional"], 
      directions: "Shake the other ingredients with ice, then carefully pour into the glass. Served: On the roc\ 
ks; poured over ice. Optional: Salt the rim of the glass by rubbing lime on it so it sticks." 
    }, 
    { 
      id: "2", 
      name: "Strawberry Margarita", 
      ingredients: ["Tequila", "Lime juice","Triple Sec","Strawberries","Lime","Salt", "Ice"], 
      measurements: ["2 oz","1 oz", "1 oz", "3 1/2 cups", "1", "optional", "optional"], 
      directions: "Combine strawberries, ice, tequila, lime juice, and triple sec in a blender, and process unt\ 
il the mixture is smooth. Carefully pour into the glass. Served: On the rocks; poured over ice. Optional: Salt the ri\ 
m of the glass by rubbing lime on it so it sticks." 
    }]; 

    db.collection('drinks', function(err, collection) { 
      collection.insert(drinks, {safe:true}, function(err, result) {}); 
     }); 
}; 

警告是:

express deprecated app.configure: Check app.get('env') in an if statement server.js:6:5 
connect deprecated multipart: use parser (multiparty, busboy, formidable) npm module instead node_modules/express/node_modules/connect/lib/middleware/bodyParser.js:56:20 
connect deprecated limit: Restrict request size at location of read node_modules/express/node_modules/connect/lib/middleware/multipart.js:86:15 
+0

將一些console.log()語句添加到您的代碼中,以查明它到底有多遠。作爲一個出發點 - 在你的findAll函數中,甚至可能在app.get('/ drinks',..)的回調中。 – Tim

+0

你確定你的數據庫已經啓動了嗎?如果是,它是綁定到27017? –

+0

好吧,我做到了這一點,它與線collection.find()。toArray(函數(錯誤,飲料){res.send(飲料);}); @Tim – Zach

回答

0

你的模型(drinks.js)接受兩個參數(REQ & RES),但在你的路線上,你不會傳入任何參數。

嘗試以下操作:

app.get('/drinks', function(req, res) { 
    drink.findAll(req, res); 
}); 

app.get('/drinks/:id', function(req, res){ 
    drink.findById(req, res); 
}); 

或者,你可以實現一個基於回調結構相同:

server.js

...

app.get('/drinks', function(req, res) { 
    drink.findAll(function(err, drinks){ 
     res.send(drinks) 
    }); 
}); 

。 ..

drinks.js

...(所需的錯誤處理)

exports.findAll = function(callback) { 
    db.collection('drinks', function(err, collection) { 
      collection.find().toArray(function(err, drinks) { 
        callback(err, drinks) 
       }); 
     }); 
}; 

...

+0

我添加了這些行和ReferenceError:請求沒有定義 – Zach

1

我認爲阿什利是在正確的軌道上。但是,爲了更清楚問題出在哪裏發生了嘗試使用此作爲指南: http://expressjs.com/en/guide/routing.html

app.get('/drinks', function (req, res) { 
    drink.findAll(req, res); 
}); 

然後你就可以添加此調用之間,並在你的函數findAll登錄。

+0

謝謝蒂姆,我認爲我的方法會說話,但可能不會。我會更新我的答案。 –

相關問題