2016-11-23 13 views
0

Node.jsにシンプルな残りのAPIを開発しています。 は、これは私のコントローラのコードです:Node.jsが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); 
       }         
      }); 
     }); 

答えて

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); 
}); 
+0

正常に動作します。ありがとう! –

1

ベストプラクティスは、エラーとして最初の引数であるとresult.Youとして第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); 
    }); 
}); 
+0

うまく動作します!ありがとう! –

関連する問題