javascript - express 发送文件和重定向网址

标签 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 发送到他们所在的任何 url。我怎样才能将它们重定向到“/”并提供 index.html 而不会弄乱任何 future 的中间件。

最佳答案

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

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

关于javascript - express 发送文件和重定向网址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19900557/

相关文章:

javascript - 动态导入在 netlify 中不起作用(reactjs)

javascript - 对象作为突变 : GraphQL - Apollo - React 中的输入变量

node.js - 从 mongoDB 获取最后 30 条记录

javascript - 确定 JavaScript 属性是否定义了 getter 或 setter?

javascript - 为什么 D3 对输入的关注仅在第一次起作用?

javascript - 调用 JavaScript Action 时修改样式 - prettyPhoto lightbox

node.js - 将不需要的功能(fdescribe、describe.only)检测为 Gulp 任务

Django 接受 GET 参数

javascript - 获取从javascript url传递的参数

Django:用户配置文件的动态 URL