简体   繁体   English

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

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

I have a basic express app and I want to serve one file (after performing some logic) for the default route of / . 我有一个基本的express应用,我想为/的默认路由提供一个文件(执行一些逻辑后)。

Unfortunately I can't use 不幸的是我不能使用

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

express.static()

because that will intercept every request and send the filepath for every request. 因为这将拦截每个请求并发送每个请求的文件filepath

Is there another way of doing this? 还有另一种方法吗?

It's enough to check the URI part of url and if it's / then send file. 检查url的URI部分,如果它是/然后发送文件,就足够了。

Check this: 检查一下:

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

or: 要么:

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

this may work comment your requirement 这可能会评论您的要求

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

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