快速发送文件和重定向网址 [英] Express sendfile and redirect url

查看:73
本文介绍了快速发送文件和重定向网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a bunch of middleware. At the first app.use I test if the process is under duress, and if so I want it to just send the static /index.html file and redirect the user's browser to "/#" + 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发送到他们所在的任何url.如何将它们重定向到"/"并提供index.html,而又不会弄乱任何将来的中间件.

Right now, it just sends the index.html to whatever url they're at. How can I redirect them to "/" and serve index.html without messing up any future middleware.

推荐答案

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

Not sure if I understand correctly, but try this:

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(...));

这篇关于快速发送文件和重定向网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆