快速发送文件和重定向 URL

Express sendfile and redirect url

本文关键字:重定向 URL 文件      更新时间:2023-09-26

我有一堆中间件。在第一个app.use,我测试该过程是否受到胁迫,如果是这样,我希望它只发送静态/index.html文件并将用户的浏览器重定向到"/#" + req.url

例如:

app.set("port", PORT)
//etc
app.use(function(req, res, next) {
  if (something)
    res.sendfile('/public/index.html', { root: __dirname + '/..' })
    // also, redirect the user to '/#' + req.url
  else
    next()
});
// a ton more middleware that deals with the main site
app.use(express.static(...))

现在,它只是将索引.html发送到他们所在的任何网址。如何将它们重定向到"/"并提供索引.html而不会弄乱任何未来的中间件。

不确定我是否正确理解,但请尝试以下操作:

app.use(function(req, res, next) {
  if (something && req.path !== '/')
    return res.redirect('/');
  next();
});
app.get('/', function(req, res, next) {
  if (something)
    return res.sendfile('/public/index.html', { root: __dirname + '/..' });
  next();
});
app.use(express.static(...));