简体   繁体   中英

Defining root and error routes in NodeJs/Express

I defined some routes for my application. Like

app.get('/page1', function (req, res) {
    res.render('page1');
});

app.get('/page2', function (req, res) {
    res.render('page2');
});

and if the route is missing or wrong, the application should always redirect to another page. I want to define a root route:

app.get('/', function (req, res) {
    res.render('notFound'); // redirect to a 404 template
});

and what do I have to define to cover all the error or missing pages?

When having '/page1/abcdefgh' and '/fooBar' both routes should redirect to the res.render('notFound'); template.

To handle a 404 place a * route-handler below all pre-defined routes. So if none of your predefined routes will match (like /page1 or /page2 ), the * will get triggered.

// Will match /page1
app.get('/page1', function (req, res) {
    res.render('page1');
});

// Will match /page2
app.get('/page2', function (req, res) {
    res.render('page2');
});

// Will be triggered if nothing above got a match
app.get('*', function (req, res) {
    res.render('notFound'); // redirect to a 404 template
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM