如何拒绝 Express 静态服务 index.html?

4
当我通过Node Express提供Angular 5应用程序时,当我访问 domain.com 时,Express静态服务将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
@vibhor1997a 是的,正确的。 - O-mkar
3个回答

10

找到了解决方案

var options = {
  index: false
}

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

索引:发送指定的目录索引文件。将其设置为 false 可禁用目录索引。

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


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'));
});

这将涵盖您所有的请求。但是以这种方式,您将不得不在两个路由中编写相同的代码。

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')));

2
你遗漏了一个重要的部分,这个代码必须放在 app.use(express.static(...)) 之前,这样 / 请求就会在到达 express.static() 中间件之前被处理。 - jfriend00
@Ishan Thilina Somasiri,它不起作用,也不是我要求的。 - O-mkar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接