There are several different methods available for building AngularJS applications and shipping those applications for production. 

One way to build Angular application is with NodeJS or Java, and the other method is in which we first build Angular, serve the static content with NGINX. If we are using it with NodeJS, then we also need to deal with server code. For example, the index.html page must be loaded with node.

AngularJS is a framework of JavaScript, and this framework does not load itself with the browser; some external or extra mechanisms or methodologies are needed for loading Angular applications. NodeJS takes part in loading the AngularJS application with all the dependencies, such as CSS files and JS files in the browser. For loading all the assets of Angular and accepting all the API calls from the AngularJS applications, NodeJS is generally used as a web server.

Post Graduate Program: Full Stack Web Development

in Collaboration with Caltech CTMEEnroll Now
Post Graduate Program: Full Stack Web Development

Prerequisites:

  • NodeJS must be installed on our laptops. 
  • We should know the working of http.
  • Few other things are also required to be present in our system if we want to practice or run this, for instance, Angular CLI, TypeScript, VS code, and ngx-bootstrap.

Now, we will go through an example project so we can get a demonstrative idea of building AngularJS applications with NodeJS.

Example Project:

Here in this example, we will build a simple application where the users can be added, counted, and displayed at the side. The users can also be retrieved as per our wish.

Whenever the users are added, API calls are made to the NodeJS server for storing all the user data, and also, the API calls are made for getting the same user data when we want to retrieve them.

For the source code of the example application, you can visit the GitHub repo. From here, clone the code to your system. After cloning, install the npm by typing npm install and start the project (type npm start).

What Is NodeJS?

NodeJS is generally an asynchronous event-driven framework of JavaScript for server-side applications. The current version of NodeJS can be installed from the provided link https://nodejs.org/en/. For installing it on your laptop, you can click any of the LTS links. After the NodeJS package gets downloaded, you can install it in your system.

The version for NodeJS can be checked by using the command node -v. 

JavaScript can be run in the Node REPL by typing node on the command line interface. 

Angular_Node_1.

After installing node, you can even run the JavaScript files. First, you need to create a JavaScript file, such as test.js, and then you can run the JavaScript file using the command node test.js.

Here’s the sample code, which you can run in your test.js.

var a = 10;

var b = 20;

var c = a + b;

console.log(c);

//expected output is 30

Output:

Angular_Node_2

Now let us discuss the development phase.

New Course: Full Stack Development for Beginners

Learn Git Command, Angular, NodeJS, Maven & MoreEnroll Now
New Course: Full Stack Development for Beginners

Development Phase

NodeJS server and the Angular application run on two different ports in the development phase, making it easier and faster to implement while developing an application. For example, in the development phase, we can say that with the help of the webpack dev server, AngularJS application is running on port 4200, whereas the NodeJS server is running on port no. 3080.

Angular_Node_3.

Project Structure

Within our project, there are two package.json files: 

  • Angular application
  • NodeJS APIs.

It is considered good practice to have two different node_modules for Angular and NodeJS. No merging issues will be created, or there will be no problems like web server and node module collision if we have two different node_modules in AngularJS and NodeJS server.

All the files of the AngularJS application will be stored under the <your_application_name> folder, whereas all the NodeJS API will be stored inside the root folder. For the NodeJS API, we can have a separate folder too.

NodeJS API

Express and nodemon are used on the server side. For NodeJS, express is considered as the non-opinionated, fast, and minimalist web framework. Whereas whenever there is a change in the files, the nodemon makes our API load automatically. As nodemon is used for development, it should be installed in dev dependency. 

For installing the two dependencies, you need to run the following commands:

npm install express --save

npm install nodemon --save-dev

For the node.js API, the package.json will appear as shown below:

{

    "name": "angular-nodejs-example",

    "version": "1.0.0",

    "description": "node server",

    "main": "index.js",

    "scripts": {

      "start": "node index.js",

      "dev": "nodemon ./server.js localhost 3080",

      "test": "echo \"Error: no test specified\" && exit 1"

    },

    "repository": {

      "type": "git",

      "url": "git+https://github.com/bbachi/angular-nodejs-example.git"

    },

    "author": "Bhargav Bachina",

    "license": "ISC",

    "bugs": {

      "url": "https://github.com/bbachi/angular-nodejs-example/issues"

    },

    "homepage": "https://github.com/bbachi/angular-nodejs-example#readme",

    "dependencies": {

      "express": "^4.17.1"

    },

    "devDependencies": {

      "nodemon": "^2.0.2"

    }

  }

The express is needed to be imported, and then we need to define two routes: one for /api/users, and another for /api/user. Here, the server server.js file is listening to port no. 3080. For handling the data in an HTTP request object, we use the body parser.

Below is the code implementation for the same:

const express = require('express');

const app = express(),

      bodyParser = require("body-parser");

      port = 3080;

const users = [];

app.use(bodyParser.json());

app.get('/api/users', (req, res) => {

  res.json(users);

});

app.post('/api/user', (req, res) => {

  const user = req.body.user;

  users.push(user);

  res.json("user added");

});

app.get('/', (req,res) => {

    res.send('App Works !');

});

app.listen(port, () => {

    console.log(`Server listening on the port no.:${port}`);

});

With the command npm run dev, the NodeJS API gets started, and if any changes are made in the files, those changes will be automatically updated by nodemon.

Now that we know that the NodeJS application is running on port no. 3080, let us look into the Angular application. 

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

Angular App

All the files of the Angular application are under a separate folder that can be created using the command ng new <your_app_name>.

Let us check out the service file through which the Node API is called here.

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Injectable({

  providedIn: 'root'

})

export class AppService {

  constructor(private http: HttpClient) { }

  rootURL = '/api';

  getUsers() {

    return this.http.get(this.rootURL + '/users');

  }

  addUser(user: any) {

    return this.http.post(this.rootURL + '/user', {user});

  }

}

Below is the app component through which all the calls are subscribed and all the data is received from the API.

import { Injectable } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Injectable({

  providedIn: 'root'

})

export class AppService {

  constructor(private http: HttpClient) { }

  rootURL = '/api';

  getUsers() {

    return this.http.get(this.rootURL + '/users');

  }

  addUser(user: any) {

    return this.http.post(this.rootURL + '/user', {user});

  }

}

Interaction Procedure Between Node API and Angular Application 

As we know, with the help of the webpack dev server, the Angular application is running on port no. 4200, and the Node API is running on port no. 3080 in the development phase. For the interaction of these two, we can proxy all the API calls to NodeJS. Angular provides an inbuilt proxy method. Under your application folder, first, the proxy.conf.json file must be defined.

Here is the code for this file:

{

    "/api": {

      "target": "http://localhost:3080",

      "secure": false

    }

  }

All the files which are starting with /api will be directed to http://localhost:3080. This is the port where the NodeJS API is running. Then you need to define angular.json under the server part of the proxyConfig key.

Once this is configured, the Angular application can run on port 4200 and the NodeJS API on 3080; these two can still run together.

For the NodeJS API, in the first terminal, you need to run npm run dev, and in the second terminal for the Angular application, you need to run npm start.

Now let us go through the procedure by which we can build the project for production. 

Building Project for Production

Our Angular application is running on port no. 4200 with the help of webpack dev server. This cannot be possible in the production phase because we need to apply different mechanisms. First, you need to build the Angular project and load all the static assets in the node server. 

Let us go through the steps in detail:

  1. Build the Angular project using the command npm run build, and then put all the assets built under the dist folder.
  2. The server side needs to be modified next, which means we need to make the changes in our server.js file.
  3. At line no. 9, express.static needs to be used. We do this so that express gets to know that there is a dist folder, and within that folder, all the built assets for the AngularJS application are present.
  4. Then, at the default route “/” at line 22, we need to load the index.html.

Here is the modified code:

const express = require('express');

const app = express(),

      bodyParser = require("body-parser");

      port = 3080;

const users = [];

app.use(bodyParser.json());

app.use(express.static(process.cwd()+"/my-app/dist/angular-nodejs-example/"));

app.get('/api/users', (req, res) => {

  res.json(users);

});

app.post('/api/user', (req, res) => {

  const user = req.body.user;

  users.push(user);

  res.json("user added");

});

app.get('/', (req,res) => {

  res.sendFile(process.cwd()+"/my-app/dist/angular-nodejs-example/index.html")

});

app.listen(port, () => {

    console.log(`Server listening on the port no.:${port}`);

});

After making all the necessary modifications, we can run our whole application with the NodeJS server, which is running on port no. 3080, and where the NodeJS also acts like a web server.

Free Course: Programming Fundamentals

Learn the Basics of ProgrammingEnroll Now
Free Course: Programming Fundamentals

Packaging Angular Project for Production

We can package and ship the Angular app to production in multiple ways.

Manual Implementation

Here, we have to build the Angular app, place the appropriate code into one folder, and then run or deploy the application. 

Packaging With Gulp

With the help of Gulp, the process of passing the appropriate files and codes can be automated. 

With Webpack

For building the Angular code, a webpack is used internally by Angular CLI to build and bundle the entire code into a few files. The same can be used for NodeJS server too. This way, we can skip the installation of all the dependencies to run the app. 

With Docker

In this method of implementation, all the files are placed in the Docker file system, and a Docker image is created.

Here, you need to run the Docker images on some container platforms, such as Docker, EKS, ECS, etc. 

While building the Docker images, multi-stage builds are used mainly for avoiding the hectic use of different tools and bundlers for putting all the files together and packaging it. With tools such as gulps or grunt, the tasks can be automated. 

For deploying in a Packaged app, AWS ECS Beanstalk is an easier option.

Deploying on AWS Elastic Beanstalk

AWS Elastic Beanstalk is the easiest solution for quickly deploying any application without any kind of worry about the underlying infrastructure. For taking care of the provisioning underlying infrastructures, such as EC2 instances, auto calling groups, monitoring, etc., at the time of uploading .zip or .war file, you can always seek support of AWS Elastic Beanstalk. 

Creating an IAM group with limited permissions and adding a user to that group is always preferable instead of using root credentials after creating an AWS account. 

Gulp can be used for building the project; for uploading, a zip archive can be created. However, an appropriate platform must be chosen for uploading the zip archive.

Setting up the Elastic Beanstalk takes only a few minutes. 

The environment can be debugged, and the logs can be requested if something goes wrong on the details page. We can use version labels for updating and deploying the environment; we need to terminate the deployment for cleaning the resources. 

In the zip archive, there must be a package.json, and we need to make sure that the nodeJs server is listening to port no. 8080. The port can be easily configured by using the environment variable PORT in the application code, 

Deploying on AWS ECS

Once the packaging is done, we can deploy this application to AWS ECS

Amazon Elastic Container Service or Amazon ECS is considered as a highly scalable and fast container management service. It helps in running, stopping, and managing the Docker containers on a cluster of Amazon EC2 resources. 

An Amazon ECS launch type, EC2 or Fargate, can be specified when running a standalone task or creating a service to determine the infrastructure on which your tasks and services are hosted. 

There is no need to provision, configure or scale the clusters of the VM or virtual machines when we are using AWS Fargate. 

The EC2 launch type can be used to run your containerized applications on Amazon EC2 instances that you register to your Amazon ECS cluster and manage yourself.

If we want the Amazon ECS container agent to call to the Amazon ECS API on our behalf, then the AmazonEC2ContainerServiceforEC2Role policy must be added to the users. We can use any Docker Image Registry, such as Docker Hub or AWS ECR.

Summary

  • Angular applications can be built and shipped for production in many different ways.
  • AngularJS and NodeJS API can be run on the different port numbers when they are in the development phase.
  • Interaction between Angular and Node is made by proxying all the calls to API.
  • Angular application is built in the production phase. Then in the dist folder, all the assets are put and loaded with the node server.
  • The express is needed to know where the assets of AngularJS are stored.
  • Then the application can be packaged using any of the available methods.
  • Soon after packaging, the application can be deployed on any of the node environments.
Advance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now!

Conclusion

In this article, we learned about building an application with AngularJS and NodeJS. Angular Node is extremely useful for server-side rendering and processing and also for other websites as NodeJS is a non-blocking IO.

If you want to learn more about Angular Node and other topics related to Application Development, you can enroll in the Full Stack Web Development Certificate Course provided by Simplilearn. 

You can also join Simplilearn’s SkillUp platform for free courses and advance in your career with certificates and specializations. The courses in the SkillUp program are designed to enhance your knowledge and skills and improve your career prospects. For more information on these programs, visit Simplilearn.

About the Author

Ravikiran A SRavikiran A S

Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.