在 Nodejs 中的 URL 中隐藏索引.html



试图使用 nodejs 和 express 从 url 中隐藏单词"index",就像 example.com/一样(或者没有/甚至更好(。我让它重定向到/并在/index 上显示页面,但想知道我是否可以删除/index 并只显示/,但是渲染只发生在/index 而不是/上。

app.get('/', function (req, res) { 
//called on / but just redirects url to /index I do not want to duplicate the rendering code here
res.redirect('/index') });  //to redirect / to index.html
}
app.get('/:slug', function(req, res){
//renders the page here but only called if /index in url not on /
}

更新:谢谢,我实际上正在尝试使 :slug 可选,因此即使只是/like:slug 似乎不能为空,也会以某种方式执行第二个语句?

您应该呈现index.html

而不是重定向
app.get('/', function (req, res) { 
res.sendFile(__dirname + '/index.html');
} 

好吧,当您尝试从一个端点重定向到另一个端点时,通常会使用重定向,在那里您将传递目标端点的 URL。 您正在做的是重定向到 HTML 页面,这就是它附加到 URL 中的原因。 您应该在重定向时使用一些诱人的引擎,例如(jade,hbs(,否则您可以简单地使用sendFile方法来呈现静态html文件。 检查下面的代码。

app.get('/', (req, res) => { 
res.sendFile(__dirname + '/index.html');
}); 

谢谢大家,但我试图避免单独渲染它。查看快速路由,我发现 url 的行为类似于正则表达式,因此只需添加一个 ?使 :slug 可选。

app.get(/:slug?) function (req, res) { 
//slug will be undefined for just / so
if(!slug) slug = 'index';
//render the appropriate page
} 

最新更新