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?
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!
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]
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
above router.get, you should have:-
// serve angular front end files from root path
router.use('/', express.static('public', { redirect: false }));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.