我一直在挖掘这个话题很长一段时间,并尝试了很多不起作用的方法。如果您使用 angular-cli 和 express ,如果所选答案不适合您,我找到了解决方案。
Try this node module : express-history-api-fallback
[ Angular ] Change your app.module.ts file , under @NgModule > imports as following :
RouterModule.forRoot(routes), ...
This is so called : " Location Strategy "
You probably were using " Hash Location Strategy " like this :
RouterModule.forRoot(routes, { useHash: true }) , ...
[ Express & Node ]
Basically you have to handle the URL properly , so if you want call "api/datas" etc. that doesn't conflict with the HTML5 Location Strategy .
In your server.js file ( if you used express generator , I've rename it as middleware.js for clarity )
Step 1. - Require the express-history-api-fallback module.
const fallback = require('express-history-api-fallback');
Step 2 . You may have a lot of routes module , sth. like :
app.use('/api/users, userRoutes);
app.use('/api/books, bookRoutes); ......
app.use('/', index); // Where you render your Angular 4 (dist/index.html)
Becareful with the order you are writing , in my case I call the module right under app.use('/',index);
app.use(fallback(__dirname + '/dist/index.html'));
* Make sure it is before where you handle 404 or sth. like that .
This approach works for me : )
I am using EAN stack (Angular4 with cli , Express , Node )