【问题标题】:Node.js doesn't show results status properly in apiNode.js 无法在 api 中正确显示结果状态
【发布时间】:2017-04-08 03:13:53
【问题描述】:

我正在 Node.js 中开发一个简单的 rest API,它的工作原理中等。 这是我的控制器代码:

...
exports.listById = function(id, callback) {
        Course.findById(id, function(err, courses){
            if(err){
                callback({error: 'Not Found'});
            }
            else{
                callback(courses);
            }
        });        
    }

这是我的路线:

app.get('/courses/:id', function(req, res){
        var id = req.params.id;
        courseController.listById(id, function(resp){
            res.status(200).json(resp);                                 
        });
    });

此代码有效并在 mongodb 中显示我的集合结果。 但是下面的代码没有显示邮递员的结果:

app.get('/courses/:id', function(req, res){
            var id = req.params.id;
            courseController.listById(id, function(err, resp){

            if(err){
                    res.status(404).send(err);
               }
               else{
                    res.status(200).json(resp);
               }                                 
            });
        });

【问题讨论】:

    标签: javascript node.js mongodb api mongoose


    【解决方案1】:
    exports.listById = function(id, callback) {
        Course.findById(id, function(err, courses){
            if(err)
                return callback(new Error('Not Found')); // You must return Error by standard
    
            callback(null, courses); // You must set first argument (error) to null
        });        
    }
    ...
    // You can check that id is number
    app.get('/courses/:id(\\d+)', function(req, res, next) { 
        var id = req.params.id;
        courseController.listById(id, function(err, resp) {
    
        if(err)
            return next(err); // Pass error to error-handler (see link below)
    
        res.status(200).json(resp);
    });
    

    【讨论】:

      【解决方案2】:

      回调函数的最佳实践是第一个参数作为错误,第二个作为结果。你应该

      exports.listById = function (id, callback) {
          Course.findById(id, function (err, courses) {
              if (err) {
                  callback(error);
              }
              else {
                  callback(null, courses);
              }
          });
      }
      

      而你的路线应该是这样的:

      app.get('/courses/:id', function (req, res) {
          var id = req.params.id;
          courseController.listById(id, function (error, courses) {
              if (error) return res.status(500) // internal server error
      
              // if I remember correctly, sources is empty array if course not found
              res.status(200).json(resp);
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-30
        • 1970-01-01
        • 2021-01-25
        • 2022-01-18
        • 2016-03-02
        • 2023-03-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多