I am using Angular CLI and additionally I added a server folder which includes the server.js file.
1) I created the folder server within the src folder
2) npm install express --save added the express dependencies
3) Created within the server folder the server.js file
const express = require('express');
var app = express();
var staticRoot = __dirname;
app.set('port', (process.env.PORT || 3000));
app.use(express.static(staticRoot));
app.get('/', function(req, res) {
res.sendFile('index.html', { root: path.join(__dirname, '../') });
});
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
4) My index.html file is the same path which Angular CLI created
->src->index.html

Well my question is what is the next step to run my application over the server express server?
Can I also add the node server/server.js as script to run the server and client at the same time? After ng build I am not getting a server.js file within the dist folder?

The index.html that you are referencing is used in the build process, not locally. As a standalone angular app, ng serve will run angular on localhost:4200 by default. To make it point to your back end server, You can use a proxy to make angular requests going to /api redirect to your server on localhost:3000. Locally, you'll just have to run the server and angular apps separately.
In a production environment, you'll need to serve static files from your /dist directory. Your server has to check that it's running in production, and serve files using path.resolve:
const path = require("path");
const express = require('express');
const app = express();
app.set('port', (process.env.PORT || 3000));
app.set('env', (process.env.NODE_ENV || "local"));
if (app.get('env') === 'production') {
// the relative path from src/server/server.js
const staticRoot = path.resolve(__dirname, '../../dist');
app.use(express.static(staticRoot));
app.get('/', function(req, res) {
res.sendFile('index.html', { root: staticRoot });
});
}
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With