【问题标题】:Unable to retrieve data from API using Express NodeJS and MongoDB, loading无法使用 Express NodeJS 和 MongoDB 从 API 检索数据,正在加载
【发布时间】:2015-12-23 23:43:27
【问题描述】:

我正在尝试使用 Node.js、Express 和 MongoDB 创建一个 Rest API。我目前正在我的本地主机上运行:3000。当我尝试重新启动并运行服务器时,我正在使用路由 http://localhost:3000/drinks

我使用 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

【问题讨论】:

  • 将一些 console.log() 语句添加到您的代码中,以了解它的进展情况。作为起点 - 在您的 findAll 函数中,甚至可能在您的 app.get('/drinks',..) 的回调中
  • 你确定你的数据库已经启动了吗?如果是,是否绑定到 27017 ?
  • 好的,我这样做了,但是行 collection.find().toArray(function(err, Drinks) {res.send(drinks);}); @蒂姆
  • 检查是否返回错误:if (err){ console.error('err:',err);}
  • 我添加了那行代码,@Tim 没有返回错误

标签: javascript node.js mongodb express


【解决方案1】:

我认为 Ashley 走在了正确的轨道上。但为了更清楚问题发生在哪里,请尝试使用以下指南: http://expressjs.com/en/guide/routing.html

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

然后您可以在此调用之间和您的 findAll 函数中添加登录。

【讨论】:

  • 谢谢蒂姆,我以为我的方法会说话,但也许不会。我会更新我的答案。
【解决方案2】:

您的模型 (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)
                });
        });
};

(需要错误处理) ...

【讨论】:

  • 我添加了这些行和 ReferenceError: req is not defined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-26
  • 2019-06-09
相关资源
最近更新 更多