Wesley Heron Wesley Heron - 23 days ago 8
Javascript Question

Node.js doesn't show results status properly in api

I'm developing a simple rest API in Node.js, and it works middling.
This is my controller code:

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


And this is my route:

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


This code works and show results of my collection in mongodb.
But the code below, doesn't show results with postman:

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

Answer Source
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);
});