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

依然范特西╮ 提交于 2019-12-02 20:37:53
H82b1

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!