【问题标题】:Express static serves index.html How to deny it?快递静态服务 index.html 怎么拒绝呢?
【发布时间】:2018-06-11 20:50:02
【问题描述】:

当我从 node express 提供我的 angular 5 应用程序时,我在访问 domain.com 时遇到了这个问题,因为 express static 服务 index.html 但是当我访问 domain.com/something 它正常工作可以帮助我如何解决这个问题

app.use(express.static(path.join(__dirname, 'dist'))); //This line serves index.html how to deny it

app.use("/api", routes);

app.get('*', function(req, res) { //The reason it needs to be * so that it works with angular routes or it wont work

//This is never called when i visit domain.com. but it does when i visit domain.com/somthing

   console.log("i was serverd"); 
   res.sendFile(path.join(__dirname, 'dist/index.html'));
});

提前致谢:)

【问题讨论】:

  • 你想在你的路由中服务dist/index.html而不是express.static吗?
  • @vibhor1997a 是正确的

标签: node.js angular express


【解决方案1】:

找到解决方案

var options = {
  index: false
}

app.use(express.static(path.join(__dirname, 'dist'), options));

index :发送指定目录索引文件。设置为 false 以禁用目录索引。

参考:http://expressjs.com/en/api.html

【讨论】:

    【解决方案2】:

    我为您的问题找到了解决方法

     app.use('/',(req,res,next)=>{
      if(req.path!='/')
        next();
      console.log('ii');
      res.sendFile(path.join(__dirname,'dist/index.html'));
    },express.static(path.join(__dirname, 'dist')));
    
    app.get('*',(req,res,next)=>{
      console.log('ii');
      res.sendFile(path.join(__dirname,'dist/index.html'));
    });
    

    这将涵盖您的所有请求。但是这样你就必须在 2 个路由中编写相同的代码

    【讨论】:

      【解决方案3】:

      * 替换为/

      这应该在app.use(express.static 调用之前注册。 (谢谢jfriend00

      例如:

       app.get('/', function(req, res) { //see, no asterix
      
          //This is never called when i visit domain.com. but it does when i visit domain.com/somthing
      
             console.log("i was serverd"); 
             res.sendFile(path.join(__dirname, 'dist/index.html'));
          });
      
      app.use(express.static(path.join(__dirname, 'dist')));
      

      【讨论】:

      • 你遗漏了一个重要的部分,它必须放在app.use(express.static(...)) 行之前,以便/ 请求在到达express.static() 中间件之前得到处理。
      • @Ishan Thilina Somasiri 它不起作用,这不是我要求的。
      猜你喜欢
      • 2018-06-11
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 2014-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      相关资源
      最近更新 更多