Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.static handling root url request

express.static is handling the root url request. e.g. I want to do a redirect in express from https://example.com to https://example.com/dashboard. Check the cases below, first one works, second does not. I expect the second to work too. Anyone knows why?

Case 1 (works)

app.get('/', (req, res, next) => {
   res.redirect('/dashboard');
})    

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

app.get('/dashboard', (req, res, next) => {
   //do stuff
}) 

Case 2 (does not work for me)

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

//request doesn't come here 
app.get('/', (req, res, next) => {   
   res.redirect('/dashboard')
})

app.get('/dashboard', (req, res, next) => {
  //do some stuff
}) 
like image 474
maxcc00 Avatar asked Sep 13 '17 17:09

maxcc00


People also ask

How do you serve static assets in Express?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

What does Express static () return?

use() function executes middleware in order. The express. static() middleware returns an HTTP 404 if it can't find a file, so that means you should typically call app.

What does Express Router () do?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

How do I Express request?

Express. js Request and Response objects are the parameters of the callback function which is used in Express applications. The express. js request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.


1 Answers

That would happen if there's a file dist/index.html, because that's what express.static() would look for when retrieving a directory (in this case /).

You can turn that behaviour off like this:

app.use(express.static(path.join(__dirname, 'dist'), { index : false }))

Documented here: http://expressjs.com/en/4x/api.html#express.static

like image 56
robertklep Avatar answered Oct 09 '22 05:10

robertklep