I am using Angular2 app with Express.
I have this url /v2/tickets?filterId=321. Upon reloading the page, the url gets changed to /v2/tickets/?filterId=321. This breaks my Angular2 routing.
In the chrome network calls, I see 301 being thrown.
This is my simple server configuration:
app.use('/v2', express.static(path.join(__dirname + '/dist')));
app.use('/v2/*', express.static(path.join(__dirname + '/dist')));
Any ideas, Why is this redirection happening and how can I prevent it ?
The redict occurs because the redict is the default in serve-static. You can disable it with express.static('dir', { redirect: false }) but then /v2/tickets could not be found and returns 404. E.g. express-static has the same behavior.
Do you have a base set (like <base href="/v2">), and return the index.html for everything this isn't your api route like
app.get('/v2/*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'))
})
because i don't know how this could work with the code you have posted.
Apart from that the redict would not be a problem if you would not use url params, because angular would remove the trailing slash automatically. If /v2/tickets/321 would also work, this would be the easiest solution with a better looking url.
If you need the url param and want to use express and serve-static, maybe it would be easier to add a trailing slash to your path in the routing.
Personaly i prefer to have a nginx for the static files, because it is faster, has better caching, more options, ... and forward all api requests to to node like
location /api {
proxy_pass http://api;
}
location / {
try_files $uri /index.html;
}