Develop A Web Project With Authentication Using MEAN Stack

Introduction 

 
In today's Web-based application work, MEAN stack is one of the popular web development stacks. MEAN stack mainly consists of MongoDB, Express, Angular, and Node.js. MEAN has become much popular because it allows us to develop a program in JavaScript on both the client-side and server-side. The MEAN stack always enables a perfect combination of JavaScript Object Notation (JSON) development like MongoDB stores data in a JSON-like format, Express, and Node.js provide facility easy JSON based query creation and Angular allows the client to seamlessly send and receive the JSON documents.
 
MEAN is mainly used to develop a browser-based web application since Angular (client-side) and Express (server-side) are both the frameworks related to the web applications. Also using MEAN stack, we can develop a RESTful API Server with the help of Express and Node.js very easily. Since the RESTful API server is required to provide support related to the API endpoint so that those can be accessed from any applications or devices.
 
The application we will develop in this article is a basic Product Catalog that supports standard CRUD (Create, Read, Update, Delete) operations along with the authentication mechanism. So that nobody can access the product catalog without proper authorization. For the authorization purpose, we will use the JWT tokens and shown how to implement JWT token in this MEAN stack based application. For this purpose, we will break down this article into the below sub-category or parts. 
  1. Create a Basic Projects structure using Angular CLI.
  2. Develop API Server using Express to Insert Initial Data into Mongo Database
  3. Develop CRUD related API
  4. Develop Product List UI using Angular
  5. Develop UI for Add New Product in the List
  6. Implement API wrapper service
  7. Implement Router in Express App
  8. Create JWT token and implement in API endpoints for Authentication
  9. Implement Http Interceptor to pass a token from Angular Component to API request
  10. Implement User Login Screen to generate the token
  11. Implement the Route guard so that nobody can access product list UI without proper authentication.
Prerequisites
 
For developing this MEAN stack-based web application, the below-mentioned software needs to be installed in our machine.
  1. Node.js (Latest Version)
  2. MongoDB
  3. Angular CLI 10 (Latest Version)

Project Structure

 
First, we need to create a blank folder structure for the MEAN stack-based web application. For that purpose, we will create the below project structure:
 
 
In the above image, we can see that we create two folder name client (this folder will contain all files related to the client-side application which is used in Angular 10) and server (this folder contains all files related server-side operation like initial data insert through API, express app, etc.) under the src folder. Within the client folder, we create blank Angular CLI Projects which contain all files related to the Angular CLI project structure.
 
Now, we need to include some extra packages in the package.json which will help us to develop this MEAN stack-based application. Also, we include two new script based commands (sample to insert initialize data into MongoDB & start to run both the App i.e. Angular & Express at a time) to initialize the API server using express App.
  1. {  
  2.   "name""ng-product-manager",  
  3.   "version""0.0.0",  
  4.   "scripts": {  
  5.     "ng""ng",  
  6.     "start""run-s build start:server" 
  7.     "serve""ng serve",  
  8.     "build""ng build --prod",  
  9.     "start:server""node src/server/index.js",  
  10.     "watch:client""ng serve --proxy-config proxy.conf.json --open",  
  11.     "server""npx nodemon src/server/index.js",  
  12.     "watch""run-p watch:*",  
  13.     "sample""node src/server/sampledata/initialize-db.js" 
  14.     "test""ng test",  
  15.     "lint""ng lint",  
  16.     "e2e""ng e2e"  
  17.   },  
  18.   "private"true,  
  19.   "dependencies": {  
  20.     "@angular/animations""~10.0.0",  
  21.     "@angular/common""~10.0.0",  
  22.     "@angular/compiler""~10.0.0",  
  23.     "@angular/core""~10.0.0",  
  24.     "@angular/forms""~10.0.0",  
  25.     "@angular/platform-browser""~10.0.0",  
  26.     "@angular/platform-browser-dynamic""~10.0.0",  
  27.     "@angular/router""~10.0.0",  
  28.     "bcrypt""^5.0.0",  
  29.     "body-parser""^1.19.0",  
  30.     "core-js""^3.6.5",  
  31.     "dotenv""^8.2.0",  
  32.     "express""^4.17.1",  
  33.     "express-jwt""^5.3.3",  
  34.     "jsonwebtoken""^8.5.1",  
  35.     "mongodb""^3.5.9",  
  36.     "npm-run-all""^4.1.5",  
  37.     "rxjs""~6.5.5",  
  38.     "tslib""^2.0.0",  
  39.     "zone.js""~0.10.3"  
  40.   },  
  41.   "devDependencies": {  
  42.     "@angular-devkit/build-angular""~0.1000.0",  
  43.     "@angular/cli""~10.0.0",  
  44.     "@angular/compiler-cli""~10.0.0",  
  45.     "@types/jasmine""~3.5.0",  
  46.     "@types/jasminewd2""~2.0.3",  
  47.     "@types/node""^12.11.1",  
  48.     "codelyzer""^6.0.0-next.1",  
  49.     "jasmine-core""~3.5.0",  
  50.     "jasmine-spec-reporter""~5.0.0",  
  51.     "karma""~5.0.0",  
  52.     "karma-chrome-launcher""~3.1.0",  
  53.     "karma-coverage-istanbul-reporter""~3.0.2",  
  54.     "karma-jasmine""~3.3.0",  
  55.     "karma-jasmine-html-reporter""^1.5.0",  
  56.     "nodemon""^2.0.4",  
  57.     "protractor""~7.0.0",  
  58.     "ts-node""~8.3.0",  
  59.     "tslint""~6.1.0",  
  60.     "typescript""~3.9.5"  
  61.   }  
  62. }  

Develop API using Express to Insert Initial Data Into Mongo Database

 
Step 1
 
Now, add a new file named .env to store some key-pair value related to the environment. In this file, we will keep the MongoDB server URL along with Database Name. 
  1. DB_CONN=mongodb://127.0.0.1:27017/ProductCatelog  
  2. DB_NAME = ProductCatelog  
Step 2
 
Add another file named proxy.conf.json which is used to define the proxy setting for the RESTfull API server.
  1. {  
  2.   "/api": {  
  3.     "target""http://localhost:3000",  
  4.     "secure"false  
  5.   }    
  6. }  
Step 3
 
Now go to the SampleData folder under the server folder. This folder already contains two JSON files named users.json and  products.json which contain some initial data related to the product and user. Now, add a new file named initialize-db.js within the folder and write down the below code within that file. The code written in this file is used to insert the initial record into the MongoDB. For that, we first read the .env environment file where we already mentioned the server details related to MongoDB. Then we also create an instance of Mongo DB and pass those credentials along with Collection name to insert those records into the Mongo DB. 
  1. require('dotenv').config();  
  2.   
  3. const {MongoClient} = require('mongodb');  
  4. const bcrypt = require('bcrypt');  
  5.   
  6. const users = require('./users');  
  7. const products = require('./products');  
  8.   
  9. async function initializeDBRecords(collectionName, data){  
  10.           
  11.     const client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  12.     await client.connect();  
  13.        
  14.     data.forEach((item) => {  
  15.         if (item.password) {  
  16.             item.password = bcrypt.hashSync(item.password, 10);  
  17.         }  
  18.     });  
  19.       
  20.     const result = await client.db(process.env.DB_NAME).collection(collectionName).insertMany(data);  
  21.   
  22.     console.log(`${result.insertedCount} new listing(s) created with the following id(s):`);  
  23.     console.log(result.insertedIds);  
  24.     client.close  
  25.     console.log("Clossing Connections");  
  26. }  
  27.   
  28. initializeDBRecords('Users', users);  
  29. initializeDBRecords('Products', products);  
Now, open the command prompt and run the below command to execute the initialize-db.js file.
  1. npm run sample  
After running the above command, it will show the below result (we can check in Mongo DB Database either data inserted or not)
 
 

Develop CRUD Related API

 
Now, its time to develop the CRUD related API. For that purpose, we will add a new file named index.js under the server folder and the below code:
  1. const express = require('express');  
  2. const app = express();  
  3.   
  4. const {MongoClient} = require('mongodb');  
  5. const bodyParser = require('body-parser');  
  6.   
  7. const path = require('path');  
  8.   
  9. require('dotenv').config();  
  10.   
  11. app.use(express.static(path.join(__dirname, 'public')));  
  12. app.use('/images', express.static(path.join(__dirname, 'images')));  
  13. app.use(bodyParser.json());  
  14.   
  15. let mongoclient;  
  16.   
  17. console.log('Server Started');  
  18.   
  19. async function initializeDBConnections(){  
  20.           
  21.     let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  22.     await client.connect();  
  23.   
  24.     console.log("Database connection ready");  
  25.   
  26.     // Initialize the app.  
  27.     app.listen(3000, () => {  
  28.         mongoclient= client;  
  29.         console.log("App Run in Port 3000");  
  30.     });  
  31. }  
  32.   
  33. initializeDBConnections();  
  34.   
  35. app.get('/api/products', async (req, res) => {  
  36.   
  37.     let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  38.     await client.connect();  
  39.   
  40.     const cursor = await client.db(process.env.DB_NAME).collection('Products')  
  41.                         .find({});  
  42.   
  43.     const result = await cursor.toArray((err, docs) => {  
  44.          return res.json(docs)  
  45.     });  
  46. });  
  47.   
  48. app.post('/api/products', async(req,res) => {  
  49.     const product = req.body;  
  50.   
  51.     let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  52.     await client.connect();  
  53.   
  54.     const productCollection = await client.db(process.env.DB_NAME).collection('Products');  
  55.   
  56.     productCollection.insertOne(product, (err, r) => {  
  57.     if (err) {  
  58.       return res.status(500).json({ error: 'Error inserting new record.' });  
  59.     }  
  60.   
  61.     const newRecord = r.ops[0];  
  62.   
  63.     return res.status(201).json(newRecord);  
  64.   });  
  65.   
  66. });  
  67.   
  68. app.get('*', (req, res) => {  
  69.   return res.sendFile(path.join(__dirname, 'public/index.html'))  
  70. });  
Now run the below command to start the RESTful API server   
  1. npm run server  
The output of the above command, as shown below:
 
 
 
Now to check either API is working on not, open the POSTMAN and execute the Get API Command:
 
 

Develop Product List UI

 
So, after completing the CRUD API, we need to develop a Product List UI where Product Get API will be executed and as per the record return from the API, product list details will be populated. For that purpose, we need to perform the below steps:
 
Step 1
 
Create a folder named shared under the client/app folder and then create a file called product.model.ts to define the Product model objects.
  1. export interface Product {  
  2.   itemName: string;  
  3.   category: string;  
  4.   price: number;  
  5.   quantity: number;  
  6.   isStockAvailable:boolean;  
  7.   photoUrl:string;  
  8. }  
Step 2
 
Add another folder called menu and add the menu component within this folder.
 
menu.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-menu',  
  5.   templateUrl: './menu.component.html'  
  6. })  
  7. export class MenuComponent implements OnInit {  
  8.   
  9.   constructor() { }  
  10.   
  11.   ngOnInit() {  
  12.   }  
  13.   
  14. }  
menu.component.html
  1. <div class="ui menu header">  
  2.   <div class="ui container">  
  3.     <div class="item">  
  4.       <i class="icon users large blue"></i>  
  5.     </div>  
  6.     <div class="header item">  
  7.       <h1>Product Manager</h1>  
  8.     </div>  
  9.   </div>  
  10. </div>  
Step 3
 
Now add another folder named product and add the product component which will display the product details along with a product image
 
product.component.ts
  1. import { Component, OnInit, Input, HostBinding } from '@angular/core';  
  2. import { Product } from '../shared/product.model';  
  3.   
  4. @Component({  
  5.   selector: 'app-product',  
  6.   templateUrl: './product.component.html'  
  7. })  
  8. export class ProductComponent implements OnInit {  
  9.   
  10.   @Input() product: Product;  
  11.   
  12.   @HostBinding('class') columnClass = 'four wide column';  
  13.   
  14.   constructor() { }  
  15.   
  16.   ngOnInit() {  
  17.   }  
  18.   
  19. }  
product.component.html 
  1. <div class="ui card">  
  2.   <div class="image">  
  3.     <img [src]="product?.photoUrl">  
  4.   </div>  
  5.   <div class="content">  
  6.     <a class="header">{{product.itemName}}</a>      
  7.     <div class="description">  
  8.       <span>       
  9.         <span>Price : {{product.price | currency:'INR'}}</span>  
  10.       </span>  
  11.     </div>  
  12.   </div>    
  13.   <div class="extra content">  
  14.     <div class="description">  
  15.       <span>Category : {{product.category}}</span>  
  16.     </div>  
  17.     <div class="description">  
  18.       <span>  
  19.         <span>In Stocks : {{product.quantity}}</span>  
  20.       </span>  
  21.     </div>  
  22.   </div>  
  23. </div>  
Step 4
 
Now add a new folder named product-list and add the product list component which will fetch data from the product api and populate product list. To display product information, we will use the product component as a child component within the product list component.
 
product-list.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
  3. import { Product } from '../shared/product.model';  
  4. import { Observable } from 'rxjs';  
  5.   
  6. @Component({  
  7.   selector: 'app-product-list',  
  8.   templateUrl: './product-list.component.html'  
  9. })  
  10. export class ProductListComponent implements OnInit {  
  11.   
  12.   products: Array<Product>;  
  13.   
  14.   constructor(public http: HttpClient) { }  
  15.   
  16.   ngOnInit() {  
  17.     this.loadData().subscribe((data) => {  
  18.       this.products = data  
  19.     });  
  20.   }  
  21.   
  22.   private loadData(): Observable<any> {  
  23.     return this.http.get<any>('/api/products');  
  24.   }  
  25. }  
product-list.component.html 
  1. <div class="ui container">  
  2.   <div class="ui grid">  
  3.     <app-product *ngFor="let product of products" [product]="product"></app-product>  
  4.   </div>  
  5. </div>  
Step 5
 
Now add the Product list information in the routing module. 
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { ProductListComponent } from './product-list/product-list.component';  
  4.   
  5. const routes: Routes = [  
  6.   {  
  7.     path: '',  
  8.     redirectTo: 'products',  
  9.     pathMatch: 'full'  
  10.   },  
  11.   {  
  12.     path: 'products',  
  13.     component: ProductListComponent  
  14.   }  
  15. ];  
  16.   
  17. @NgModule({  
  18.   imports: [RouterModule.forRoot(routes)],  
  19.   exports: [RouterModule]  
  20. })  
  21. export class AppRoutingModule { }  
Step 6
 
Now add the all newly added component in the app.module.ts file
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpClientModule } from '@angular/common/http';  
  5.   
  6. import { AppRoutingModule } from './app-routing.module';  
  7. import { AppHomeComponent } from './app.component';  
  8. import { MenuComponent } from './menu/menu.component';  
  9. import { ProductListComponent } from './product-list/product-list.component';  
  10. import { ProductComponent } from './product/product.component';  
  11.   
  12. @NgModule({  
  13.   declarations: [  
  14.     AppHomeComponent,  
  15.     MenuComponent,  
  16.     ProductListComponent,  
  17.     ProductComponent  
  18.   ],  
  19.   imports: [  
  20.     BrowserModule,  
  21.     FormsModule,  
  22.     HttpClientModule,  
  23.     AppRoutingModule  
  24.   ],  
  25.   providers: [],  
  26.   bootstrap: [AppHomeComponent]  
  27. })  
  28. export class ProductManagerModule { }  
Step 7
 
Now change the html part code of AppHomeComponent to place the router container in the application.
  1. <app-menu></app-menu>  
  2. <router-outlet></router-outlet>  
Step 8
 
Now run the below command to execute the application.
  1. npm start  
After running the command, the application opens in the browser in localhost 3000 port as shown below:
 
 

Develop Add Product UI Component

 
Now, we need to develop a component through which we can add new products within the Product List component. For that purpose, first, we need to add the addproduct component as shown below.
 
app-product.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import { HttpClient, HttpResponse, HttpHeaders } from '@angular/common/http';  
  3. import { Product } from '../shared/product.model';  
  4. import { Observable } from 'rxjs';  
  5. import { NgForm } from '@angular/forms';  
  6.   
  7. @Component({  
  8.   selector: 'app-add-product',  
  9.   templateUrl: './add-product.component.html',  
  10.   styleUrls: ['./add-product.component.scss']  
  11. })  
  12. export class AddProductComponent implements OnInit {  
  13.   
  14.   loading: Boolean = false;  
  15.   newProduct: Product;  
  16.   
  17.   constructor(public http: HttpClient) { }  
  18.   
  19.   ngOnInit() {  
  20.   }  
  21.   
  22.   onSubmit(form: NgForm) {  
  23.     this.loading = true;  
  24.     debugger;  
  25.     const formValues = Object.assign({}, form.value);  
  26.   
  27.     const product: Product = {  
  28.       itemName: formValues.itemName,  
  29.       category: formValues.category,  
  30.       price: formValues.price,  
  31.       quantity:formValues.quantity,  
  32.       isStockAvailable: formValues.quantity>0 ? true : false,  
  33.       photoUrl: formValues.photo  
  34.     };  
  35.   
  36.     const httpOptions = {  
  37.       headers: new HttpHeaders({  
  38.         'Content-Type''application/json; charset=utf-8'  
  39.       })  
  40.     };  
  41.     this.http.post("/api/products", product, httpOptions)  
  42.       .subscribe((res: Response) => {  
  43.         debugger;  
  44.         form.reset();  
  45.         this.loading = false;  
  46.         this.newProduct = product;  
  47.       });      
  48.   }  
  49. }  
app-product.component.html
  1. <div class="add-form-container">  
  2.   <div class="ui icon message" *ngIf="newProduct">  
  3.     <i class="notched check green icon"></i>  
  4.     <i class="close icon" (click)="newProduct = null"></i>  
  5.     <div class="content">  
  6.       <div class="header">  
  7.         New Product added!  
  8.       </div>  
  9.       <p>Product Name: {{newProduct.itemName}}</p>  
  10.     </div>  
  11.   </div>  
  12.   <form class="ui big form" #productForm="ngForm" (submit)="onSubmit(productForm)" [class.loading]="loading">  
  13.     <div class="fields">  
  14.       <div class="eight wide field">  
  15.         <label>Product Name</label>  
  16.         <input type="text" placeholder="Product Name" name="itemName" ngModel>  
  17.       </div>  
  18.       <div class="eight wide field">  
  19.         <label>Product Category</label>  
  20.         <input type="text" placeholder="Product Category" name="category" ngModel>  
  21.       </div>  
  22.     </div>  
  23.     <div class="field">  
  24.       <label>Price</label>  
  25.       <input type="number" placeholder="Price" placeholder="#######.##" name="price" ngModel>  
  26.     </div>  
  27.     <div class="field">  
  28.       <label>Quantity</label>  
  29.       <input type="number" maxlength="4" placeholder="####" name="quantity" ngModel>  
  30.     </div>  
  31.     <div class="field">  
  32.       <label>Photo URL</label>  
  33.       <input type="text" placeholder="http://cdn.com/image.jpg" name="photo" ngModel>  
  34.     </div>  
  35.     <button type="submit" class="ui submit large grey button right floated">Submit</button>  
  36.   </form>  
  37. </div>  
Now add the Add Product option in the menu.component.html file.
  1. <div class="ui menu header">  
  2.   <div class="ui container">  
  3.     <div class="item">  
  4.       <a [routerLink]="['/products']" aria-label="Products">  
  5.         <i class="icon users large blue" aria-hidden="true"></i>  
  6.       </a>  
  7.     </div>  
  8.     <div class="header item">  
  9.       <h1>Product Manager</h1>  
  10.     </div>  
  11.   </div>  
  12.   <div class="item">  
  13.     <button [routerLink]="['/newproduct']" class="ui basic button">  
  14.       <i class="add user icon" aria-hidden="true"></i>  
  15.       Add Product  
  16.     </button>  
  17.   </div>  
  18. </div>  
Now add the reference of the add-product component in both the routing module and app module.
 
app-routing.module.ts
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { ProductListComponent } from './product-list/product-list.component';  
  4. import { AddProductComponent } from  './add-product/add-product.component' 
  5.   
  6. const routes: Routes = [  
  7.   {  
  8.     path: '',  
  9.     redirectTo: 'products',  
  10.     pathMatch: 'full'  
  11.   },  
  12.   {  
  13.     path: 'products',  
  14.     component: ProductListComponent  
  15.   },  
  16.   {  
  17.     path: 'newproduct',  
  18.     component: AddProductComponent  
  19.   }  
  20. ];  
  21.   
  22. @NgModule({  
  23.   imports: [RouterModule.forRoot(routes)],  
  24.   exports: [RouterModule]  
  25. })  
  26. export class AppRoutingModule { }  
app.module.ts
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpClientModule } from '@angular/common/http';  
  5.   
  6. import { AppRoutingModule } from './app-routing.module';  
  7. import { AppHomeComponent } from './app.component';  
  8. import { MenuComponent } from './menu/menu.component';  
  9. import { ProductListComponent } from './product-list/product-list.component';  
  10. import { ProductComponent } from './product/product.component';  
  11. import { AddProductComponent } from  './add-product/add-product.component' 
  12.   
  13. @NgModule({  
  14.   declarations: [  
  15.     AppHomeComponent,  
  16.     MenuComponent,  
  17.     ProductListComponent,  
  18.     ProductComponent,  
  19.     AddProductComponent  
  20.   ],  
  21.   imports: [  
  22.     BrowserModule,  
  23.     FormsModule,  
  24.     HttpClientModule,  
  25.     AppRoutingModule  
  26.   ],  
  27.   providers: [],  
  28.   bootstrap: [AppHomeComponent]  
  29. })  
  30. export class ProductManagerModule { }  
Now run the application again to check the output:
 
 

Implement API Wrapper Service

 
Since we already complete the API operations, but still we need to implement Angular HTTPClient Module call in all the components from where we want to communicate with the API server. That's why we will create an API communication service that will be responsible for any type of API communication. We will inject this API communication service into our component to invoke the API call. For that purpose, we will add a new service under the shared folder called api.service.ts. 
  1. import { Injectable } from '@angular/core';  
  2. import { HttpClient, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';  
  3. import { map } from 'rxjs/operators';  
  4. import { Observable } from 'rxjs';  
  5. import { environment } from '../../environments/environment';  
  6.   
  7. @Injectable()  
  8. export class ApiService {  
  9.   
  10.   private baseUrl = environment.apiUrl;  
  11.   
  12.   constructor(private http: HttpClient) { }  
  13.   
  14.   subscribeFunction(res: any): any { return null };  
  15.     
  16.   errorFunction(res: any): any { return res };  
  17.   
  18.   subscribe(r: any): any {  
  19.     this.subscribeFunction = r;  
  20.       return this;  
  21.   };  
  22.   
  23.   error(e: any): any {  
  24.       this.errorFunction = e;  
  25.       return this;  
  26.   };  
  27.   
  28.   get(url: string) {  
  29.     return this.request(url, "GET");  
  30.   }  
  31.   
  32.   post(url: string, body: Object) {  
  33.     return this.request(url, "POST", body);  
  34.   }  
  35.   
  36.   put(url: string, body: Object) {  
  37.     return this.request(url, "PUT", body);  
  38.   }  
  39.   
  40.   delete(url: string) {  
  41.     return this.request(url, "DELETE");  
  42.   }  
  43.   
  44.   request(url: string, method: string, body?: Object) : any {  
  45.     const headers = new HttpHeaders();  
  46.     headers.append('Content-Type''application/json');  
  47.     const finalUrl =`${this.baseUrl}/${url}`;  
  48.       
  49.     var request;  
  50.     if (body) {  
  51.       request = new HttpRequest(method, finalUrl,body,{headers:headers, responseType:'json'});  
  52.     }  
  53.     else{  
  54.       request = new HttpRequest(method, finalUrl,{headers:headers});  
  55.     }  
  56.      
  57.     let serviceObject=this;  
  58.     this.http.request(request)  
  59.              .subscribe((res: HttpResponse<any>) =>{  
  60.                if (serviceObject.subscribeFunction != null) {  
  61.                 serviceObject.subscribeFunction(res.body);  
  62.               }  
  63.              },  
  64.              (error: HttpResponse<any>) => {  
  65.                 const statusCode = error.status;  
  66.                 const body = error.statusText;  
  67.   
  68.                 const errorMessage = {  
  69.                   statusCode: statusCode,  
  70.                   error: body  
  71.                 };  
  72.   
  73.                 console.log(errorMessage);  
  74.                 return Observable.throw(error);                
  75.             }  
  76.              );  
  77.     return this;  
  78.   }  
  79.   
  80. }  
Now, inject this file within the product list component as shown below:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Product } from '../shared/product.model';  
  3. import { Observable } from 'rxjs';  
  4. import { ApiService } from '../shared/api.service';  
  5.   
  6. @Component({  
  7.   selector: 'app-product-list',  
  8.   templateUrl: './product-list.component.html'  
  9. })  
  10. export class ProductListComponent implements OnInit {  
  11.   
  12.   products: Array<Product>;  
  13.   
  14.   constructor(public http: ApiService) { }  
  15.   
  16.   ngOnInit() {  
  17.     this.loadData().subscribe((data) => {  
  18.       this.products = data;  
  19.     });  
  20.   }  
  21.   
  22.   private loadData(): Observable<any> {  
  23.     return this.http.get('products');  
  24.   }  
  25. }  
Also, you need to add the ap.service.ts into the app.module.ts file. 
  1. import { BrowserModule } from '@angular/platform-browser';  
  2. import { NgModule } from '@angular/core';  
  3. import { FormsModule } from '@angular/forms';  
  4. import { HttpClientModule } from '@angular/common/http';  
  5.   
  6. import { AppRoutingModule } from './app-routing.module';  
  7. import { AppHomeComponent } from './app.component';  
  8. import { MenuComponent } from './menu/menu.component';  
  9. import { ProductListComponent } from './product-list/product-list.component';  
  10. import { ProductComponent } from './product/product.component';  
  11. import { AddContactComponent } from  './add-product/add-product.component';  
  12.   
  13. import { ApiService } from './shared/api.service';  
  14.   
  15. @NgModule({  
  16.   declarations: [  
  17.     AppHomeComponent,  
  18.     MenuComponent,  
  19.     ProductListComponent,  
  20.     ProductComponent,  
  21.     AddContactComponent  
  22.   ],  
  23.   imports: [  
  24.     BrowserModule,  
  25.     FormsModule,  
  26.     HttpClientModule,  
  27.     AppRoutingModule  
  28.   ],  
  29.   providers: [ApiService],  
  30.   bootstrap: [AppHomeComponent]  
  31. })  
  32. export class ProductManagerModule { }  

Implement Router in Express App

 
Now, we need to implement the API router in the express app. Since, we need to implement the API router and then intialize that API router through the Express App. For that purpose, first, we need to create api-router.js file and add the below code:
  1. const express = require('express');  
  2. const {MongoClient} = require('mongodb');  
  3. const jwt = require('jsonwebtoken');  
  4. const bcrypt = require('bcrypt');  
  5.   
  6. function apiRouter() {  
  7.   const router = express.Router();  
  8.   
  9.     router.get('/products', async (req, res) => {  
  10.   
  11.         let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  12.         await client.connect();  
  13.   
  14.         const cursor = await client.db(process.env.DB_NAME).collection('Products')  
  15.                             .find({});  
  16.   
  17.         const result = await cursor.toArray((err, docs) => {  
  18.             return res.json(docs)  
  19.         });  
  20.     });  
  21.   
  22.     router.post('/api/products', async(req,res) => {  
  23.         const product = req.body;  
  24.       
  25.         let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  26.         await client.connect();  
  27.       
  28.         const productCollection = await client.db(process.env.DB_NAME).collection('Products');  
  29.       
  30.         productCollection.insertOne(product, (err, r) => {  
  31.         if (err) {  
  32.           return res.status(500).json({ error: 'Error inserting new record.' });  
  33.         }  
  34.       
  35.         const newRecord = r.ops[0];  
  36.       
  37.         return res.status(201).json(newRecord);  
  38.       });  
  39.       
  40.     });  
  41.   
  42.   return router;  
  43. }  
  44.   
  45. module.exports = apiRouter;  
Now, add another file called create-express-app.js file and add the below code:
  1. const express = require('express');  
  2. const bodyParser = require('body-parser');  
  3. const path = require('path');  
  4. const apiRouter = require('./api-router');  
  5.   
  6. function createExpressApp() {  
  7.   const app = express();  
  8.   
  9.   app.use(express.static(path.join(__dirname, 'public')));  
  10.   app.use('/images', express.static(path.join(__dirname, 'images')));  
  11.   app.use(bodyParser.json());  
  12.   app.use('/api', apiRouter());  
  13.   app.use('*', (req, res) => {  
  14.     return res.sendFile(path.join(__dirname, 'public/index.html'))  
  15.   });  
  16.   
  17.   return app;  
  18. }  
  19.   
  20. module.exports = createExpressApp;  
Also, the remove the API communication-related code from the index.js  file.
  1. const express = require('express');  
  2. const app = express();  
  3.   
  4. const {MongoClient} = require('mongodb');  
  5. const bodyParser = require('body-parser');  
  6.   
  7. const path = require('path');  
  8.   
  9. const createExpressApp = require('./create-express-app');  
  10.   
  11. require('dotenv').config();  
  12.   
  13. let mongoclient;  
  14.   
  15. console.log('Server Started');  
  16.   
  17. async function initializeDBConnections(){  
  18.           
  19.     let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  20.     await client.connect();  
  21.   
  22.     console.log("Database connection ready");  
  23.   
  24.     // Initialize the app.  
  25.     createExpressApp().listen(3000, () => {  
  26.         mongoclient= client;  
  27.         console.log("App Run in Port 3000");  
  28.     });  
  29. }  
  30.   
  31. initializeDBConnections();  

Create a JWT Token and Implement an API Endpoint

 
Now, we need to implement authentication in the API. For that purpose, we will implement the JWT token for authentication purposes. For activate JWT token, we first need to provide a JWT secret in the .env file. If you need to generate the JWT secret then that can be retrieved from this URL. Now, after putting the JWT secret, need to make changes in the API-router.js file. We need to check the JWT token before any API router and also, we will create a new API endpoint for authentication purposes. This endpoint accepts the user name and password as input and generates and returns the token if the provided user name and password matched with the stored user name and password in the Mongo DB user collection. 
  1. const express = require('express');  
  2. const {MongoClient} = require('mongodb');  
  3. const jwt = require('jsonwebtoken');  
  4. const bcrypt = require('bcrypt');  
  5. const checkJwt = require('express-jwt');  
  6.   
  7. function apiRouter() {  
  8.   const router = express.Router();  
  9.   
  10.   router.use(  
  11.     checkJwt({ secret: process.env.JWT_SECRET }).unless({ path: '/api/authenticate'})  
  12.   );  
  13.   
  14.   router.use((err, req, res, next) => {  
  15.     if (err.name === 'UnauthorizedError') {  
  16.       res.status(401).send({ error: err.message });  
  17.     }  
  18.   });  
  19.   
  20.     router.get('/products', async (req, res) => {  
  21.   
  22.         let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  23.         await client.connect();  
  24.   
  25.         const cursor = await client.db(process.env.DB_NAME).collection('Products')  
  26.                             .find({});  
  27.   
  28.         const result = await cursor.toArray((err, docs) => {  
  29.             return res.json(docs)  
  30.         });  
  31.     });  
  32.   
  33.     router.post('/products', async(req,res) => {  
  34.         const product = req.body;  
  35.       
  36.         let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  37.         await client.connect();  
  38.       
  39.         const productCollection = await client.db(process.env.DB_NAME).collection('Products');  
  40.       
  41.         productCollection.insertOne(product, (err, r) => {  
  42.         if (err) {  
  43.           return res.status(500).json({ error: 'Error inserting new record.' });  
  44.         }  
  45.       
  46.         const newRecord = r.ops[0];  
  47.       
  48.         return res.status(201).json(newRecord);  
  49.       });  
  50.       
  51.     });  
  52.   
  53.     router.post('/authenticate', async(req, res) => {  
  54.       const user = req.body;  
  55.         
  56.       let client = new MongoClient(process.env.DB_CONN,{ useNewUrlParser: true, useUnifiedTopology: true });  
  57.       await client.connect();  
  58.       
  59.       const usersCollection = await client.db(process.env.DB_NAME).collection('Users');  
  60.     
  61.       usersCollection  
  62.         .findOne({ username: user.username }, (err, result) => {  
  63.           if (!result) {  
  64.             return res.status(404).json({ error: 'user not found' })  
  65.           }  
  66.     
  67.           if (!bcrypt.compareSync(user.password, result.password)) {  
  68.             return res.status(401).json({ error: 'incorrect password '});  
  69.           }  
  70.     
  71.           const payload = {  
  72.             username: result.username,  
  73.             admin: result.admin  
  74.           };  
  75.     
  76.           const token = jwt.sign(payload, process.env.JWT_SECRET, { expiresIn: '4h' });  
  77.     
  78.           return res.json({  
  79.             message: 'successfuly authenticated',  
  80.             token: token  
  81.           });  
  82.         });  
  83.     });    
  84.   
  85.   return router;  
  86. }  
  87.   
  88. module.exports = apiRouter;  
Now, just goto the Postman again and try to fetch the product list data using the previous URL. Now it will throw an error message that No Authorization token was found.
 
So, from now onwards we need to first generate Token and then pass that token in the header part of the API request so that our API can be authenticated. 
 

Implement Http Interceptor to Pass token from Component to API Request

 
So, after implementing the JWT token in the API request, we can retrieve the product data through postman after passing the token value. But need to pass the token value from our angular application so that we can call the API endpoint, it will return the data from the application. For that purpose, first, we need to create a jwtinterceptor service so that it can intercept any HTTP request and push the token value within that HTTP request. So, we will add a new file called jwtinterceptor.ts file under the shared folder and add the below code:
  1. import { Injectable } from '@angular/core';  
  2. import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';  
  3. import { Observable } from 'rxjs';  
  4.   
  5. import { AuthService } from './auth.service';  
  6.   
  7. @Injectable()  
  8. export class JwtInterceptor implements HttpInterceptor {  
  9.     constructor(private authenticationService: AuthService) { }  
  10.   
  11.     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {  
  12.         const isLoggedIn = this.authenticationService.isLoggedIn();  
  13.         const token  = this.authenticationService.getToken();  
  14.         if (isLoggedIn) {  
  15.             request = request.clone({  
  16.                 setHeaders: {  
  17.                     Authorization: `Bearer ${token}`  
  18.                 }  
  19.             });  
  20.         }  
  21.   
  22.         return next.handle(request);  
  23.     }  
  24. }  
Now create another file called auth.service.ts to store and retrieve the authentication token in the client-side application.
  1. import { Injectable } from '@angular/core';  
  2. import { Router } from '@angular/router';  
  3.   
  4. @Injectable()  
  5. export class AuthService {  
  6.   
  7.   storageKey: string = 'product-manager-jwt';  
  8.   
  9.   constructor(private router: Router) { }  
  10.   
  11.   setToken(token: string) {  
  12.     localStorage.setItem(this.storageKey, token);  
  13.   }  
  14.   
  15.   getToken() {  
  16.     return localStorage.getItem(this.storageKey);  
  17.   }  
  18.   
  19.   isLoggedIn() {  
  20.     return this.getToken() !== null;  
  21.   }  
  22.   
  23.   logout() {  
  24.     localStorage.removeItem(this.storageKey);  
  25.     this.router.navigate(['/login']);  
  26.   }  
  27.   
  28. }  
Now, include the above two service reference into the app.module.ts file. 
 

Implement Login Screen

 
Now, since we already implement the authentication service and http interceptor service in the client-side application. Now we need to provide options to generate the token from the client-side application. For that purpose, we need to add Login Component in the client-side application.
 
login.component.ts
  1. import { Component, OnInit } from '@angular/core';  
  2. import { ApiService } from '../shared/api.service';  
  3. import { AuthService } from '../shared/auth.service';  
  4. import { Router } from '@angular/router';  
  5. import { NgForm } from '@angular/forms';  
  6.   
  7. @Component({  
  8.   selector: 'app-login',  
  9.   templateUrl: './login.component.html',  
  10.   styleUrls: ['./login.component.css']  
  11. })  
  12. export class LoginComponent implements OnInit {  
  13.   
  14.   constructor(private api: ApiService,private auth: AuthService,private router: Router) {  
  15.   
  16.   }  
  17.   
  18.   ngOnInit() {  
  19.   }  
  20.   
  21.   onSubmit(form: NgForm) {  
  22.     const values = form.value;  
  23.   
  24.     const payload = {  
  25.       username: values.username,  
  26.       password: values.password  
  27.     };  
  28.   
  29.     this.api.post('authenticate', payload)  
  30.       .subscribe(data => {  
  31.         if (data!=undefined){  
  32.           this.auth.setToken(data.token);  
  33.           this.router.navigate(['/products']);  
  34.         }  
  35.       });  
  36.   }  
  37.   
  38. }  
login.component.html
  1. <div class="login-container">  
  2.   <form class="ui big form" #loginForm="ngForm" (submit)="onSubmit(loginForm)">  
  3.   <div class="field">  
  4.     <label>Username</label>  
  5.     <input type="text" name="username" placeholder="Username" ngModel>  
  6.   </div>  
  7.   <div class="field">  
  8.     <label>Password</label>  
  9.     <input type="password" name="password" placeholder="Password" ngModel>  
  10.   </div>  
  11.   <button type="submit" class="ui primary button float right floated">Login</button>  
  12.   </form>  
  13. </div>  
Now, we need to add this login component in the routing module and make this login component route as a default so that when ever application start it will redirect to the login UI. 
  1. import { NgModule } from '@angular/core';  
  2. import { Routes, RouterModule } from '@angular/router';  
  3. import { ProductListComponent } from './product-list/product-list.component';  
  4. import { AddProductComponent } from  './add-product/add-product.component';  
  5. import { LoginComponent } from './login/login.component';  
  6.   
  7. import { AuthGuard } from './auth.guard';  
  8. const routes: Routes = [  
  9.   {  
  10.     path: '',  
  11.     redirectTo: 'login',  
  12.     pathMatch: 'full'  
  13.   },  
  14.   {  
  15.     path: 'products',  
  16.     component: ProductListComponent,  
  17.     canActivate:[AuthGuard]  
  18.   },  
  19.   {  
  20.     path: 'newproduct',  
  21.     component: AddProductComponent,  
  22.     canActivate:[AuthGuard]  
  23.   },  
  24.   {  
  25.     path: 'login',  
  26.     component: LoginComponent  
  27.   },  
  28.   {  
  29.     path:'**',  
  30.     redirectTo:'products'  
  31.   }  
  32. ];  
  33.   
  34. @NgModule({  
  35.   imports: [RouterModule.forRoot(routes)],  
  36.   exports: [RouterModule]  
  37. })  
  38. export class AppRoutingModule { }  
Now, create another file called auth.gaurd.ts in the same location of the routing module and add the below code to activate route guard in the client-side application.
  1. import { Injectable } from '@angular/core';  
  2. import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  
  3. import { Observable } from 'rxjs';  
  4. import { AuthService } from './shared/auth.service';  
  5. import { Router } from '@angular/router';  
  6.   
  7. @Injectable()  
  8. export class AuthGuard implements CanActivate {  
  9.   
  10.   constructor(private auth: AuthService, private router: Router) {}  
  11.   
  12.   canActivate(  
  13.     next: ActivatedRouteSnapshot,  
  14.     state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {  
  15.   
  16.     if (this.auth.isLoggedIn()) {  
  17.       return true;  
  18.     } else {  
  19.       this.router.navigate(['/login']);  
  20.       return false;  
  21.     }  
  22.   }  
  23. }  
Now, run the application with command npm run and check in the browser,
 
 

Conclusion

So, in this article, we will discuss how to develop a web-based application using MEAN stack i.e. MongoDB, Express, Angular, and NodeJs. The source code related to this article also attached along with the article. Any feedback or suggestion related to this article is always welcome.