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

时间:2013-11-11 06:58:13

标签: javascript node.js url 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(...))

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

1 个答案:

答案 0 :(得分: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(...));