2016-11-23 1 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로 첫번째 인수가해야

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

잘 작동합니다! 감사! –

관련 문제