简体   繁体   中英

How to dynamically route pages?

How would I dynamically route each page without using app.get() everytime? My code is also returning the 404 error code, also

console.log(page + " rendered");

wont work for some reason.

var express = require('express');
var path = require('path');
var ejs = require('ejs');
var app = express();


app.engine('.html', ejs.__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');


var pages = [
    'users', 
    'index'
];

pages.forEach(function(page) {
        app.get('/' + page, function(request, response) {
        response.render(page);
        console.log(page + " rendered");
    });
    console.log(page + " set up");
});

app.listen(80);
console.log('Express app started on port %d', 80);

Use regular expression in your route. ^ and $ denotes start and end of the respectively. | denotes or. Regular expression for your requirement is /^(users|index)$/ .

app.get(/^(users|index)$/, function (req, res, next) {
  response.render(req.params[0]);
  console.log(req.params[0] + " rendered");
});

This is the dynamic routing schema I'm using with express, you might be able to re-purpose it to suit your needs. It requires putting some "meta-data" into an array of objects (routes)

 "use strict"; let express = require("express"); let routing = (req, res) => { let router = express.Router(), // "meta-data" for routes routes = [{ path: "/", view: "default", title: "root" }, { path: "/otherpath", view: "otherfile", title: "otherpage" }]; // iterates through routes looking for req.path let routeIndex = routes.findIndex(route => route.path === req.path); // if object in routes found with matching path if (routeIndex >= 0) { // serves content res.status(200).render(routes[routeIndex].view, { title: routes[routeIndex].title }); } else { // else 404s console.log("404 from request: ", req.path); res.status(404).sendFile(process.cwd() + "/views/404filename.htm"); } return router }; module.exports = routing; 

Rather than creating a new route for each page, you probably want to look up the view for the url dynamically. Make sure to call next() if you don't handle the path from within your handler so that further routes and/or middleware is called.

var routes = {
    '/users': 'users rendered',
    '/index': 'index rendered',
}

app.get('*', (req, res, next) => {
    let view = routes[req.path]
    if (!view) 
        return next()
    res.render(view)        
})

app.use((req, res, next) => {
    res.status(404).send('404 - Not found')
})
app.use('/', function(req, res) {
  // whatever
});

This will match everything. Inside the callback, you can do your rendering (you can access the request via the req object to render the appropriate page). See app.use .

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