Express static serve index.html如何否认它?

时间:2018-01-02 05:36:46

标签: node.js angular express

当我从node express提供angular 5应用程序时,我遇到此问题,因为当我访问 domain.com 时,我会发现静态服务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'));
});

提前致谢:)

3 个答案:

答案 0 :(得分:4)

找到解决方案

var options = {
  index: false
}

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

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

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

答案 1 :(得分:1)

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

 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条路线中编写相同的代码

答案 2 :(得分:0)

*替换为/

这应该在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')));