Add Routes at Runtime (ExpressJs)

2019-04-10 04:12发布

问题:

I would like to add routes at run time. I read that its possible but I am not so sure how. Currently I using the following code:

var app = express();

function CreateRoute(route){
app.use(route, require('./routes/customchat.js'));
}

And customchat looks like

var express = require('express');
var router = express.Router();

router.route('/').get(function (req, res) {
var url =  req.baseUrl;
var roomname = url.substring(url.lastIndexOf('_') + 1);
res.render('chat', { name: roomname , year: new Date().getFullYear().toString()});
});

module.exports = router;

When I call the method CreateRoute before I start listening it will link the route. But when I do it at runtime it wont create a new route. My goal is to add routes add runtime. I will generate an path like /room_Date. And this should be added at runtime using the template customchat.

I am using express version 4.13.

Thanks in advance for your help.

回答1:

customchat.js should called customChat.js and be

const customChat = (req, res) => {
  const { name } =  req.params;
  const year = new Date().getFullYear().toString();
  res.render('chat', { name , year });
}

module.exports = customChat

then when you create your app

const express = require('express')
const customChat = require('./routes/customChat.js')
const app = express()

app.use('/chat/:name', customChat)

See the official Express routing docs for more information.