Tony
Tony

Reputation: 243

Angular CLI add express server

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

enter image description here

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?

enter image description here

Upvotes: 3

Views: 3114

Answers (2)

chrisbajorin
chrisbajorin

Reputation: 6153

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'));
});

Upvotes: 2

somnathbm
somnathbm

Reputation: 659

You should place the static files inside the public directory and use path.join() from NodeJS path module. You will be able to handle the path properly there.

See the following links:

res.sendFile absolute path

https://scotch.io/tutorials/use-expressjs-to-deliver-html-files

Upvotes: 0

Related Questions