【问题标题】:Express sendfile and redirect url快递发送文件和重定向网址
【发布时间】:2013-11-11 06:58:12
【问题描述】:

我有一堆中间件。在第一个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 发送到他们所在的任何 url。如何将它们重定向到“/”并提供 index.html 而不会弄乱任何未来的中间件。

【问题讨论】:

  • 您显然可以致电res.redirect('/'),但我感觉这不是您想要的?
  • 静态文件在应用中间件之后才会挂载,所以重定向到'/'不会返回任何东西。

标签: javascript node.js url express


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 2017-09-16
    • 2013-10-16
    • 2010-11-29
    • 1970-01-01
    相关资源
    最近更新 更多