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

后端 未结 2 397
傲寒
傲寒 2021-02-02 13:23

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     =         


        
相关标签:
2条回答
  • 2021-02-02 13:48

    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;
    });
    
    0 讨论(0)
  • 2021-02-02 13:57

    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.

    0 讨论(0)
提交回复
热议问题