Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express js 4 how to serve json results without rendering any views /css

I am using express 4 in order to create a json API service. I can't seem to define it to send a simple json without trying to render the view.

var express     = require('express');
var router      = express.Router();

module.exports = function (app, namespace) {
    router.get('/', function(req, res) {
        res.json({'body': 123});
    });


    app.use(namespace + '/v1', router);
};

when I access the route it's

Error: Failed to lookup view "error" in views directory "/Volumes/api_service/init/views"

I tried to remove the views engine all together

//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');

but it yells with this error

No default engine was specified and no extension was provided
like image 394
WebQube Avatar asked Apr 25 '14 14:04

WebQube


2 Answers

If you're making any calls to res.render such as in an error handler that are generated by the 'express generate', then you'll see the error you described. For a json API service you probably don't need to render anything so just don't call render(), instead call res.send() with the status res.status set to 404 or 500.

So basically, replace this:

app.use(function(err, req, res, next) {
    res.render('error', {
        message: err.message,
        error: err
    });
});

with this:

app.use(function(err, req, res, next){
    res.status(err.status || 500);
    res.send({
        message: err.message,
        error: err
    });
   return;
});
like image 194
H82b1 Avatar answered Oct 20 '22 04:10

H82b1


eventually it was the express generic catch 404's that made all the routes unvailables.

app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

removing him solved it.

like image 5
WebQube Avatar answered Oct 20 '22 05:10

WebQube