Reputation: 29
I am building my angular project and inserting the build output into a public folder in the root of my node project.
In my app.js file, I have the following code:
...
app.use(express.static(path.join(__dirname, 'public')));
...
app.get('*', (req, res) => {
res.send(path.join(__dirname, 'public/index.html'));
});
When deploying the project, this works perfectly; when I load the page, the index.html is rendered and navigating through the page works.
However, when I enter a url like for example '/admin', which is defined in my angular routing, I get a not found error.
How can this be solved?
Upvotes: 0
Views: 1956
Reputation: 565
I don't know your code but
you can try setting up the base-href in your index.html
<base href="/">
properly....
Serving with nginx could have a configuration like this. It directs the index.html to the correct routes of your SPA:
root /home/app/dist/;
server {
listen 8080;
server_name localhost;
location /admin/ {
alias /home/app/dist/my-app/admin/;
expires -1;
add_header Cache-Control "no-cache, must-revalicate, post-check=0 pre-check=0";
index index.html;
try_files $uri $uri/ index.html =404;
}
location / {
alias /home/app/dist/my-app/;
expires -1;
add_header Cache-Control "no-cache, must-revalicate, post-check=0 pre-check=0";
index index.html;
try_files $uri $uri/ index.html =404;
}
}
see nginx how-to here: https://medium.com/better-programming/how-to-properly-get-angular-and-nginx-working-together-for-development-3e5d158734bf
Upvotes: 0
Reputation: 29
The problem was in the .send() method... I replaced this:
app.get('*', (req, res) => {
res.send(path.join(__dirname, 'public/index.html'));
});
with this:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
and it worked. Sorry guys for making you loose time. You helped me research different things though!
Upvotes: 1
Reputation: 10979
above router.get, you should have :-
// serve angular front end files from root path
router.use('/', express.static('public', { redirect: false }));
Upvotes: 0
Reputation: 578
Hope this will solve ur issue Create .htaccess file in root folder and pass
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^(.*) /index.html [NC,L]
Upvotes: 0