O-mkar
O-mkar

Reputation: 5658

Express static serves index.html How to deny it?

When I serve my angular 5 app from node express I face this issue as express static serves index.html when I visit domain.com but I when I visit domain.com/something it works correctly can some help how do I solve this

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

Thanks in advance :)

Upvotes: 4

Views: 2572

Answers (3)

vibhor1997a
vibhor1997a

Reputation: 2376

I have found a workaround for your prooblem

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

This will cover for all your requests. But in this way you would have to write same code in 2 routes

Upvotes: 1

O-mkar
O-mkar

Reputation: 5658

Found a solution

var options = {
  index: false
}

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

index : Sends the specified directory index file. Set to false to disable directory indexing.

Refer: http://expressjs.com/en/api.html

Upvotes: 10

Ishan Thilina Somasiri
Ishan Thilina Somasiri

Reputation: 1244

Replace * with /.

This should be registered before the app.use(express.static call. (Thank you jfriend00)

Ex :

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

Upvotes: 0

Related Questions