在运行时添加路由(ExpressJs) [英] 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'));
}
自定义聊天看起来像
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;
当我在开始监听之前调用CreateRoute方法时,它将链接该路由。但是,当我在运行时执行此操作时,它不会创建新的路由。
我的目标是添加路由并添加运行时。我将生成类似/ room_Date的路径。这应该在运行时使用模板customchat添加。
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.
我使用的是Express版本4.13。
I am using express version 4.13.
谢谢
推荐答案
customchat.js
应该称为 customChat.js
并成为
const customChat = (req, res) => {
const { name } = req.params;
const year = new Date().getFullYear().toString();
res.render('chat', { name , year });
}
module.exports = customChat
然后当您创建您的应用
const express = require('express')
const customChat = require('./routes/customChat.js')
const app = express()
app.use('/chat/:name', customChat)
请参见官方Express路由文档以获取更多信息。
See the official Express routing docs for more information.
这篇关于在运行时添加路由(ExpressJs)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!