0

Trying to hide the word "index" from url like just example.com/ (or even better without the /) using nodejs and express. I got it to redirect on / and display the page on /index but wondering if I can remove /index and just show /, however the rendering only happens on /index not on /.

    app.get('/', function (req, res) { 
      //called on / but just redirects url to /index I do not want to duplicate the rendering code here
      res.redirect('/index') });  //to redirect / to index.html
    }
    app.get('/:slug', function(req, res){
      //renders the page here but only called if /index in url not on /
    }

UPDATE: Thanks I'm actually trying to make the :slug optional so the second statement somehow gets executed even on just / like :slug can't be empty it seems?

3 Answers 3

2

Instead of redirecting, you should render index.html

app.get('/', function (req, res) { 
   res.sendFile(__dirname + '/index.html');
} 
Sign up to request clarification or add additional context in comments.

Comments

0

Well, generally redirect is used when you're trying to redirect from one end point to another, there you'll pass the url of the targeted endpoint. what you're doing is redirecting to the html page that's why it is appending into the url. You should simply use some tempting engine like (jade, hbs) while redirecting or else you can simply use sendFile method to render static html files. Check the code below.

app.get('/', (req, res) => { 
   res.sendFile(__dirname + '/index.html');
}); 

Comments

0

Thanks guys but I was trying to avoid having to render it seperately. Looking at Express Routes I found that the urls behave like regular expressions so just adding a ? makes the :slug optional.

    app.get(/:slug?) function (req, res) { 
      //slug will be undefined for just / so
      if(!slug) slug = 'index';
      //render the appropriate page
    } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.