简体   繁体   中英

Add Routes at Runtime (ExpressJs)

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.

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.

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