在节点中的GET请求后,从mongolab获取空JSON

Getting empty JSON from mongolab after GET request in node

本文关键字:mongolab 获取 JSON 节点 GET 请求      更新时间:2023-09-26

我的问题:我正试图从数据库中随机questionSchemaHTTP.GET,但它返回""

在我的数据库(托管在mongolab中)中,我有一些不同的集合,但在我的问题集合中,我只有3个不同的JSON,其中有3个不同问题。

我有一个Schema,看起来像这样:

var questionSchema = new Schema({
    description: String    
});
module.exports = mongoose.model('Question', questionSchema);

在我的routes.js中,我放置了以下内容:

app.get('/api/getrandomquestion', function (req, res) {
        if (req.params.description) {
            res.json(req.description);
        } else {
            res.json("");
        }
    });

我还有一个名为QuestionService.js的服务,它应该查询数据库,并从那里存在的所有(3)个文档中返回一个随机JSON文档。这是服务的代码:

var numberOfItemsToFind = 3;
Question.find({}, { '_id': 1}, function(err, data){
    if (err) res.send(err);
    var arr = shuffle.(data.slice(0));
    arr.splice(numberOfItemsToFind, arr.length - numberOfItemsToFind);
    var return_arr = [];
    async.each(arr, function(item, callback){
        Question.findById(item._id, function(err, data){
            if (err) res.send(err);
            return_arr.push(data);
            callback();
        });
    }, function(err){
        res.json(return_arr);
    });
});

最后,我把这些和我的questionCtrl:放在一起

controller('QuestionCtrl', function ($scope, $http, $modal) {
    $http.get('/api/getrandomquestion').success(function (question) {
        $scope.description  = question.description;
    });
});

我正在使用POSTMAN向localhost:3000/getrandomquestion发出HTTP.GET请求,并且我只返回了我所说的""

任何帮助解决我的问题(空的JSON而不是真正的JSON)都将非常感谢!

问题出现在routes.js:中

app.get('/api/getrandomquestion', function (req, res) {
    if (req.params.description) {
        res.json(req.description);
    } else {
        res.json("");
    }
});

req.params.description未定义。所以if语句失败了。

如果参数description不是必需的,那么您可能应该这样定义GET API:

app.get('/api/getrandomquestion', function (req, res) {
   QuestionService.getRandomQuestion(function(questions){
     res.json(questions);
   //res.send(questions);
   });
});

基本上,您的后端收到一个GET getrandomquestions API调用,您只需使用QuestionService转发以获取MongoDB。