node.js - Express.js : How to serve one file for the default "/" route, 然后使用express.static 其余部分?

标签 node.js express

我有一个基本的 Express 应用程序,我想为 / 的默认路由提供一个文件(在执行一些逻辑之后)。

不幸的是我不能使用

app.use(function (res, res, next){
    *logic here*
    res.sendFile(filepath);
}); 

express.static()

因为这将拦截每个请求并发送每个请求的文件路径

还有其他方法吗?

最佳答案

检查 url 的 URI 部分就足够了,如果是/则发送文件。

检查一下:

app.use(function (req, res, next) { // first must be Your middleware
  if(req.path == '/') {
    return res.sendFile('some file');
  }

  next();
}); 

app.use(express.static('public'));  // and after it You can attach static middleware

或者:

app.use(express.static('public'));

app.all('/', function (req, res) {
  res.sendFile(filePath);
});

关于node.js - Express.js : How to serve one file for the default "/" route, 然后使用express.static 其余部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34604142/

相关文章:

node.js - 在 Express-js 中使用路由

javascript - 如何根据以前的值更新 MongoDB 文档?

javascript - 如何解决错误:Puppeteer 中的 net::ERR_CONNECTION

javascript - 在函数之后运行原型(prototype)函数

node.js - 复杂的过滤器 Sequelize js

node.js - "No listeners detected"验证错误 Mongoose 和 Mocha

javascript - Socket.IO 接受不存在的 src 标签吗?

node.js - sails.js 异步问题

node.js - 如何解决 Node.js 中的内存问题?

node.js - nodejs,socket.io : how to get request and response from socket function?