快速发送文件和重定向网址

swi*_*itz 3 javascript url node.js express

我有一堆中间件.在第一次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(...))
Run Code Online (Sandbox Code Playgroud)

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

rob*_*lep 7

不确定我是否理解正确,但试试这个:

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(...));
Run Code Online (Sandbox Code Playgroud)