Reputation: 47
I'm trying to publish a node.js server on Heroku that serves an angular app on all requests (minus /api endpoint). The angular app works perfectly fine when I run the node.js server on my local machine + running ng build --watch on the angular app. The issue I'm facing is I'm getting 404 errors on the angular routes when I push the server to Heroku.
This is the error I'm getting in Heroku logs: 2021-03-28T20:38:50.700486+00:00 app[web.1]: Error: ENOENT: no such file or directory, stat '/app/client/dist/client/index.html'
After looking into it more, I found that the dist file that is built on "npm run build" isn't deploying to heroku. Posting my package.json file below.
Here is my server code:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
const path = require('path')
const api = require('./routes/api');
const cors = require('cors')
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/api', api)
app.use(express.static(__dirname + 'client/dist/client'));
app.get('**', function(req,res) {
res.sendFile(path.join(__dirname + 'client/dist/client/index.html'));
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
console.log((path.join( __dirname + '/client/dist/client/index.html')))
})
Package.Json:
{
"name": "spotify-playlist",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^0.21.1",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
Upvotes: 0
Views: 512
Reputation: 355
A few months ago I deployed my MEAN application on Heroku so I will share my configuration with you.
In angular.json find "outputPath" and set it to the public/static folder of the server in your case. In mine it is "outputPath": "./server/static"
In the server code be sure to set the folder in which the Angular app will be built as static. In my case I have the following:
app.use(express.static(path.resolve(__basedir, 'static')))
app.get('*', (req, res) => {
res.status(200).sendFile(path.join(__basedir, '/static', 'index.html'))
});
In package.json you need the following two scripts:
"start": "node server/index.js" // This should point to your index.js file, whereever it is
"heroku-postbuild": "ng build --prod" // This one builds the angular app before your index.js serves it
P.S. Ignore the server folder in my case index.js is located inside a server folder as well as the static folder
Upvotes: 1