【问题标题】:express.static handling root url requestexpress.static 处理根 url 请求
【发布时间】:2017-09-13 17:44:40
【问题描述】:

express.static 正在处理根 url 请求。 例如我想通过快递从https://example.com 重定向到https://example.com/dashboard。 检查以下情况,第一个有效,第二个无效。我希望第二个也能工作。有谁知道为什么?

案例1(作品)

app.get('/', (req, res, next) => {
   res.redirect('/dashboard');
})    

app.use(express.static(path.join(__dirname, 'dist')))

app.get('/dashboard', (req, res, next) => {
   //do stuff
}) 

案例 2(对我不起作用)

app.use(express.static(path.join(__dirname, 'dist')))

//request doesn't come here 
app.get('/', (req, res, next) => {   
   res.redirect('/dashboard')
})

app.get('/dashboard', (req, res, next) => {
  //do some stuff
}) 

【问题讨论】:

  • 将 dist 更改为 /dist 应该可以正常工作

标签: node.js express


【解决方案1】:

如果有一个文件 dist/index.html,就会发生这种情况,因为这是 express.static() 在检索目录时会查找的内容(在本例中为 /)。

您可以像这样关闭该行为:

app.use(express.static(path.join(__dirname, 'dist'), { index : false }))

在此处记录:http://expressjs.com/en/4x/api.html#express.static

【讨论】:

  • 不错的答案! @robertklep
  • 您认为它可能会产生任何不良影响,还是没有??
  • @maxcc00 除非您确实依赖该行为(在这种情况下,替代方法是删除 dist/index.html,因为听起来您并没有真正使用它)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 2010-12-01
  • 2016-04-25
相关资源
最近更新 更多