{"id":710,"date":"2020-11-17T22:15:00","date_gmt":"2020-11-17T21:15:00","guid":{"rendered":"https:\/\/nguenkam.com\/blog\/?p=710"},"modified":"2021-01-27T13:50:29","modified_gmt":"2021-01-27T12:50:29","slug":"how-to-develop-and-build-angular-app-with-nodejs","status":"publish","type":"post","link":"https:\/\/nguenkam.com\/blog\/index.php\/2020\/11\/17\/how-to-develop-and-build-angular-app-with-nodejs\/","title":{"rendered":"How To Develop and Build Angular App With NodeJS"},"content":{"rendered":"\n<p id=\"b8ee\">There are so many ways we can build Angular apps and ship for production. One way is to build Angular with NodeJS or Java and another way is to build the angular and serve that static content with NGINX web server. With NodeJS we have to deal with the server code as well, for example, you need to load index.html page with node.<\/p>\n\n\n\n<p id=\"5de8\">In this post, we will see the details and implementation with the NodeJS. We will go through step by step with an example.<\/p>\n\n\n\n<h4>Introduction<\/h4>\n\n\n\n<p>Angular is a javascript framework for building web apps and it doesn\u2019t load itself in the browser. We need some kind of mechanism that loads the index.html (single page) of Angular with all the dependencies(CSS and js files) in the browser. In this case, we are using node as the webserver which loads Angular assets and accepts any API calls from the Angular app.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1220\/1*-3TbC_GSG93FPTaJQg0A5g.png\" alt=\"Image for post\" width=\"450\" height=\"251\"\/><\/figure>\n\n\n\n<p id=\"3e69\">If you look at the above diagram all the web requests without the&nbsp;<strong>\/api&nbsp;<\/strong>will go to Angular routing. All the paths that contain&nbsp;<strong>\/api&nbsp;<\/strong>will be handled by the Node server.<\/p>\n\n\n\n<p id=\"ec72\">In this post, we are going to develop an Angular app with NodeJS and see how to build for production.<\/p>\n\n\n\n<h4>Example Project<\/h4>\n\n\n\n<p>This is a simple project which demonstrates developing and running Angular application with NodeJS. We have a simple app in which we can add users, count, and display them at the side, and retrieve them whenever you want.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1200\/1*abg872TqJLT4IGMeCgteQw.gif\" alt=\"Image for post\" width=\"411\" height=\"239\"\/><\/figure>\n\n\n\n<p id=\"8126\">As you add users we are making an API call to the nodejs server to store them and get the same data from the server when we retrieve them. You can see network calls in the following video.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1200\/1*TjsrD4gDoeRstnn0ql2Bkg.gif\" alt=\"Image for post\" width=\"473\" height=\"275\"\/><\/figure>\n\n\n\n<p>Here is a Github link to this project. You can clone it and run it on your machine.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ clone the project\nhttps:&#47;&#47;github.com\/bbachi\/angular-nodejs-example.git\n\/\/ install and start the project\nnpm install\nnpm start<\/code><\/pre>\n\n\n\n<h4>NodeJs<\/h4>\n\n\n\n<p id=\"f198\">NodeJS is an asynchronous event-driven javascript runtime environment for server-side applications. The current version of the nodejs is&nbsp;<strong>12<\/strong>&nbsp;and you can install it from&nbsp;<a href=\"https:\/\/nodejs.org\/en\/\">this link here.<\/a>&nbsp;You can click on any LTS link and the NodeJS package is downloaded and you can install it on your laptop.<\/p>\n\n\n\n<p id=\"97d7\">You can check the version of the Node with this command&nbsp;<code>node -v.<\/code><\/p>\n\n\n\n<h4>Development Phase<\/h4>\n\n\n\n<p id=\"7d54\">Usually, the way you develop and the way you build and run in production are completely different. Thatswhy, I would like to define two phases: Development phase and Production phase.<\/p>\n\n\n\n<p id=\"b860\">In the development phase, we run the nodejs server and the Angular app on completely different ports. It\u2019s easier and faster to develop that way. If you look at the following diagram the Angular app is running on port&nbsp;<strong>4200<\/strong>&nbsp;with the help of a webpack dev server and the nodejs server is running on port&nbsp;<strong>3080<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1104\/1*Av8BtpJon1SSwGlaRZwyEw.png\" alt=\"Image for post\" width=\"358\" height=\"145\"\/><\/figure>\n\n\n\n<h4>Project Structure<\/h4>\n\n\n\n<p>Let\u2019s understand the project structure for this project. We will have two package.json: one for Angular and another for nodejs API. It\u2019s always best practice to have completely different node_modules for each one. In this way, you won\u2019t get merging issues or any other problems regarding web and server node modules collision.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1106\/1*PlIXXKQFKgLz_8iRKzCwLQ.png\" alt=\"Image for post\" width=\"486\" height=\"384\"\/><\/figure>\n\n\n\n<p>If you look at the above project structure, all the Angular app resides under the&nbsp;<strong>my-app<\/strong>&nbsp;folder and nodejs API resides under the root folder. You can have a separate folder for nodejs API as well.<\/p>\n\n\n\n<h4>NodeJs API<\/h4>\n\n\n\n<p>We use the express and nodemon on the server-side. Express is the Fast, unopinionated, minimalist web framework for NodeJS and nodemon is the library which makes your API reloads automatically whenever there is a change in the files. Let\u2019s install these two dependencies. nodemon is only used for development so install this as a dev dependency.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm install express --save\nnpm install nodemon --save-dev<\/code><\/pre>\n\n\n\n<p>Here is the&nbsp;<strong>package.json<\/strong>&nbsp;of nodejs API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"name\": \"angular-nodejs-example\",\n  \"version\": \"1.0.0\",\n  \"description\": \"node server\",\n  \"main\": \"index.js\",\n  \"scripts\": {\n    \"start\": \"node index.js\",\n    \"dev\": \"nodemon .\/server.js localhost 3080\",\n    \"test\": \"echo \\\"Error: no test specified\\\" &amp;&amp; exit 1\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https:\/\/github.com\/bbachi\/angular-nodejs-example.git\"\n  },\n  \"author\": \"Bhargav Bachina\",\n  \"license\": \"ISC\",\n  \"bugs\": {\n    \"url\": \"https:\/\/github.com\/bbachi\/angular-nodejs-example\/issues\"\n  },\n  \"homepage\": \"https:\/\/github.com\/bbachi\/angular-nodejs-example#readme\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  },\n  \"devDependencies\": {\n    \"nodemon\": \"^2.0.2\"\n  }\n}<\/code><\/pre>\n\n\n\n<p>We need to import express and define two routes:&nbsp;<strong>\/api\/users<\/strong>&nbsp;and&nbsp;<strong>\/api\/user&nbsp;<\/strong>and the server listening on the port<strong>&nbsp;3080.&nbsp;<\/strong>Here is the server.js file. We use body-parser to handle data in the http request object.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express(),\n      bodyParser = require(\"body-parser\");\n      port = 3080;\n\nconst users = &#91;];\n\napp.use(bodyParser.json());\n\napp.get('\/api\/users', (req, res) => {\n  res.json(users);\n});\n\napp.post('\/api\/user', (req, res) => {\n  const user = req.body.user;\n  users.push(user);\n  res.json(\"user addedd\");\n});\n\napp.get('\/', (req,res) => {\n    res.send('App Works !!!!');\n});\n\napp.listen(port, () => {\n    console.log(`Server listening on the port::${port}`);\n});<\/code><\/pre>\n\n\n\n<p>You need to start the nodejs API with this command&nbsp;<code><strong>npm run dev<\/strong><\/code>and the moment you change any file, it will be automatically updated.<\/p>\n\n\n\n<figure class=\"wp-block-image is-resized\"><img loading=\"lazy\" src=\"https:\/\/miro.medium.com\/max\/1200\/1*vcR3N4Yya18pnBVcr1p3Zw.gif\" alt=\"Image for post\" width=\"429\" height=\"287\"\/><\/figure>\n\n\n\n<h4>Angular App<\/h4>\n\n\n\n<p id=\"5e21\">Now the nodejs API is running on port 3080. Now it\u2019s time to look at the Angular app. The entire Angular app is under the folder my-app. You can create with this command&nbsp;<code>ng new my-app.<\/code>&nbsp;I am not going to put all the files here you can look at the entire files in the above Github link or&nbsp;<a href=\"https:\/\/github.com\/bbachi\/angular-nodejs-example\">here<\/a>.<\/p>\n\n\n\n<p id=\"dd77\">Let\u2019s see some important files here. Here is the service file which calls node API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Injectable } from '@angular\/core';\nimport { HttpClient } from '@angular\/common\/http';\n\n@Injectable({\n  providedIn: 'root'\n})\nexport class AppService {\n\n  constructor(private http: HttpClient) { }\n\n  rootURL = '\/api';\n\n  getUsers() {\n    return this.http.get(this.rootURL + '\/users');\n  }\n\n  addUser(user: any) {\n    return this.http.post(this.rootURL + '\/user', {user});\n  }\n\n}<\/code><\/pre>\n\n\n\n<p>Here is the app component which subscribes to these calls and gets the data from the API.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { Component, OnDestroy } from '@angular\/core';\nimport { FormGroup, FormControl, Validators } from '@angular\/forms';\nimport { AppService } from '.\/app.service';\nimport { takeUntil } from 'rxjs\/operators';\nimport { Subject } from 'rxjs';\n\n@Component({\n  selector: 'app-root',\n  templateUrl: '.\/app.component.html',\n  styleUrls: &#91;'.\/app.component.css']\n})\nexport class AppComponent implements OnDestroy {\n\n  constructor(private appService: AppService) {}\n\n  title = 'angular-nodejs-example';\n\n  userForm = new FormGroup({\n    firstName: new FormControl('', Validators.nullValidator &amp;&amp; Validators.required),\n    lastName: new FormControl('', Validators.nullValidator &amp;&amp; Validators.required),\n    email: new FormControl('', Validators.nullValidator &amp;&amp; Validators.required)\n  });\n\n  users: any&#91;] = &#91;];\n  userCount = 0;\n\n  destroy$: Subject&lt;boolean> = new Subject&lt;boolean>();\n\n  onSubmit() {\n    this.appService.addUser(this.userForm.value).pipe(takeUntil(this.destroy$)).subscribe(data => {\n      console.log('message::::', data);\n      this.userCount = this.userCount + 1;\n      console.log(this.userCount);\n      this.userForm.reset();\n    });\n  }\n\n  getAllUsers() {\n    this.appService.getUsers().pipe(takeUntil(this.destroy$)).subscribe((users: any&#91;]) => {\n        this.users = users;\n    });\n  }\n\n  ngOnDestroy() {\n    this.destroy$.next(true);\n    this.destroy$.unsubscribe();\n  }\n}<\/code><\/pre>\n\n\n\n<h4>Interaction between Angular and Node API<\/h4>\n\n\n\n<p id=\"b001\">n the development phase, the Angular app is running on port&nbsp;<strong>4200<\/strong>&nbsp;with the help of a webpack dev server and nodejs API running on port&nbsp;<strong>3080<\/strong>.<\/p>\n\n\n\n<p id=\"adaa\">There should be some interaction between these two. We can proxy all the API calls to nodejs API. Angular provides an inbuilt proxying method. First, we need to define the following&nbsp;<strong>proxy.conf.json<\/strong>&nbsp;under&nbsp;<strong>my-app<\/strong>&nbsp;folder.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>{\n  \"\/api\": {\n    \"target\": \"http:\/\/localhost:3080\",\n    \"secure\": false\n  }\n}<\/code><\/pre>\n\n\n\n<p>If you look at the file, all the paths that start with&nbsp;<strong>\/api&nbsp;<\/strong>will be redirected to<a href=\"http:\/\/localhost:3080.\/\"><strong>http:\/\/localhost:3080<\/strong><\/a>where the nodejs API running. Then, you need to define in angular.json under the serve part with the proxyConfig key.&nbsp;<a href=\"https:\/\/github.com\/bbachi\/angular-nodejs-example\/blob\/master\/my-app\/angular.json\">Here is the complete angular.json file.<\/a><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/miro.medium.com\/max\/1140\/1*anAg5NhVdA05Ek1ezd36rw.png\" alt=\"Image for post\"\/><\/figure>\n\n\n\n<p>Once this is configured, you can run Angular app on port 4200 and nodejs API on 3080 still make them work together.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ nodejs API (Terminal 1)\nnpm run dev\n\/\/ Angular app (Terminal 2)\nnpm start<\/code><\/pre>\n\n\n\n<h4><strong>How To Build Project For Production<\/strong><\/h4>\n\n\n\n<p id=\"c1b3\">The Angular app runs on the port&nbsp;<strong>4200<\/strong>&nbsp;with the help of a webpack dev server. This is not the case for running in production. We have to build the Angular project and load those static assets with the node server. Let\u2019s see those step by step here.<\/p>\n\n\n\n<p id=\"85bf\">First, we need to build the Angular project with this command&nbsp;<code>npm run build<\/code>&nbsp;and all the built assets will be put under the&nbsp;<strong>dist<\/strong>&nbsp;folder.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/miro.medium.com\/max\/2061\/1*XTp0mAdPzctSrly4g7kXcA.png\" alt=\"Image for post\"\/><\/figure>\n\n\n\n<p id=\"0794\">Second, we need to make some changes on the server-side. Here is the modified&nbsp;<strong>server.js<\/strong>&nbsp;file.<\/p>\n\n\n\n<ol><li>We have to use&nbsp;<strong>express.static<\/strong>&nbsp;at line number&nbsp;<strong>9<\/strong>&nbsp;to let express know there is a dist folder and assets of the Angular build. (app.use(express.static(process.cwd()+&#8221;\/my-app\/dist\/angular-nodejs-example\/&#8221;));<\/li><li>Load&nbsp;<strong>index.html&nbsp;<\/strong>for the default route<strong>&nbsp;\/&nbsp;<\/strong>at line number&nbsp;<strong>22<\/strong> (res.sendFile(process.cwd()+&#8221;\/my-app\/dist\/angular-nodejs-example\/index.html&#8221;)<\/li><\/ol>\n\n\n\n<p><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>const express = require('express');\nconst app = express(),\n      bodyParser = require(\"body-parser\");\n      port = 3080;\n\nconst users = &#91;];\n\napp.use(bodyParser.json());\napp.use(express.static(process.cwd()+\"\/my-app\/dist\/angular-nodejs-example\/\"));\n\napp.get('\/api\/users', (req, res) => {\n  res.json(users);\n});\n\napp.post('\/api\/user', (req, res) => {\n  const user = req.body.user;\n  users.push(user);\n  res.json(\"user addedd\");\n});\n\napp.get('\/', (req,res) => {\n  res.sendFile(process.cwd()+\"\/my-app\/dist\/angular-nodejs-example\/index.html\")\n});\n\napp.listen(port, () => {\n    console.log(`Server listening on the port::${port}`);\n});<\/code><\/pre>\n\n\n\n<p>Once you are done with the above changes, you can actually run the whole app with the nodejs server running on port 3080 like below as nodejs acts as a web server as well.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/miro.medium.com\/max\/1799\/1*nlvrbx_w5j4QwOAI7F-jFw.png\" alt=\"Image for post\"\/><\/figure>\n\n\n\n<h4><strong>How To Package Project For Production<\/strong><\/h4>\n\n\n\n<p>Here is a separate article on how to package this application for production. Check it out, <a href=\"https:\/\/nguenkam.com\/blog\/index.php\/2020\/11\/17\/how-to-package-angular-app-with-nodejs-backend-for-production\/\" data-type=\"post\" data-id=\"713\">here<\/a><\/p>\n\n\n\n<p>References:<\/p>\n\n\n\n<p><a href=\"https:\/\/medium.com\/\">https:\/\/medium.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>There are so many ways we can build Angular apps and ship for production. One way is to build Angular with NodeJS or Java and another way is to build the angular and serve that static content with NGINX web server. With NodeJS we have to deal with the server code as well, for example, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":716,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[37,145],"tags":[40,106,147,146,205,206],"_links":{"self":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/710"}],"collection":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/comments?post=710"}],"version-history":[{"count":4,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/710\/revisions"}],"predecessor-version":[{"id":717,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/posts\/710\/revisions\/717"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media\/716"}],"wp:attachment":[{"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/media?parent=710"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/categories?post=710"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nguenkam.com\/blog\/index.php\/wp-json\/wp\/v2\/tags?post=710"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}