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
})
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With