Wesley Heron
Wesley Heron

Reputation: 423

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

Upvotes: 0

Views: 98

Answers (2)

Aikon Mogwai
Aikon Mogwai

Reputation: 5225

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

Upvotes: 1

Simon
Simon

Reputation: 1536

Best practice for callback function is first argument as error and second as result.You should

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

while your route should look like this:

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

Upvotes: 1

Related Questions