I was trying to host my express rest service with an angular2 app on the same server. After reading varies related post I found varies solutions all worked on local server http://localhost:3000 but when hosted my app on Heroku and I try to access my express route starts with /api/... all worked well. but not able to access angular2 UI page it started showing a Not Found message on the page.
app.all('*', (req, res) => {
console.log(`[TRACE] Server 404 request: ${req.originalUrl}`);
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
or
app.use(function(req, res, next) {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
or
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
or
app.get(/^\/([^a]|a[^p]|ap[^i]|api[^/]).*$/,(req,res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
When I deployed my app on hosting server I found that dist directory does not get deployed on a server which contains Angular app build that gets created after running ng build --prod.
Firstly I manually uploaded it to the hosting server and my app started working correctly. Then it came to my mind it will be a manual task for each time so I found two solutions for this problem.
Second I read package.json documentation from this link https://docs.npmjs.com/misc/scripts and get to know about preinstall and postinstall scripts and updated my package.json file to have following scripts.
"scripts": {
"ng": "ng",
"start": "node index.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e",
"postinstall": "ng build --prod"
},
read this article for deployment on heroku https://paucls.wordpress.com/2016/11/25/deploy-angular-2-cli-app-to-heroku/