在我的Express应用程序中,我正在尝试在运行时动态添加新定义的路由。这是我的代码:
app.post('/new-user', function(req,res){
var temp = { name: "joe-bloggs", age: 20 };
users.push(temp); // users is a global variable defined earlier
var path = '/' + temp.name;
app.get(path, function(req,res){
res.send('Welcome to localhost:3000/joe-bloggs');
});
});
所以现在如果用户试图访问localhost:3000 / joe-bloggs,他们将面对欢迎消息,但是我一直得到404未找到,因为快递告诉我路线尚未定义
答案 0 :(得分:0)
只需使用req.params
为此方案制作。无需为每个用户添加其他路线。
app.get('/:username', function(req, res) {
res.send('Welcome to localhost:3000/' + req.params.username);
});