Check out some views and 404 others in express.js

this is my routing setup:

app.get('*', getJSON);

app.get('/', [list, render]);
app.get('/questions', [list, render]);
app.get('/ask', [ask, render]);

app.get('/:questionId(\\d+)', [question, render]);
app.get('/:questionId(\\d+)/:slug', [question, render]);

app.get('/sitemap.xml', clone);
app.get('/feed/qa.rss', clone);

app.post('/rest/1/:object/:method', [post, render]);
app.all('*', function(req, res){
    res.send(404).status('Page not found');
});

As you can see, almost all routes end up running a rendering function. I would like to apply the same template that I use at the beginning with getJSON, but at the end. An easy way to do this would be to add

app.all('*', render);

at the end, but I can’t because I want to skip sitemap.xml and qa.rss and all the paths not listed here, for example /foo.

How can I do that?

+4
source share
3 answers

Using

https://www.npmjs.com/package/finalhandler

as the last route. I do not use express, but express router

https://www.npmjs.com/package/router

0

. :

/middlewares/error.js

exports.notFound = function(req, res, next) {
  res.status(404);
  res.render('not-found'); // localized in /views/not-found.ejs or .html
};

// for regex error
exports.serverError = function(error, req, res, next) {
  res.status(500);
  res.render('server-error', {error: error});
};

:

app.error(function(err, req, res, next){
    if (err instanceof NotFound) {
        res.render('404.jade');
    } else if (err instanceof ServerError ){ // for regex error
        res.render('server-error.jade', {error: err});
    } else {
        next(err);
    }
});

0

You can create a router for sitemap.xml or other files:

app.get('/sitemap.xml', function(req, res) {
  app.use( function (err, xml) {
      if (err) {
         res.status(400);
         res.render('404.jade');
      } 
  });

Store the file name in an array and call it right away.

0
source

Source: https://habr.com/ru/post/1628524/


All Articles