繁体   English   中英

Express.js:如何为默认的“ /”路由提供一个文件,然后为其余文件使用express.static?

[英]Express.js: How to serve one file for the default “/” route, then use express.static for the rest?

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

不幸的是我不能使用

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

express.static()

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

还有另一种方法吗?

检查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);
});
var regexp = /^\/\w+/





app.use(function (req, res, next){
  if(!regexp.test(req.path)){
    res.sendFile(filepath);
 }  

}); 

express.static()

这可能会评论您的要求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM