Tag: MEAN Stack

  • Core Components of the MEAN Stack and Their Interaction in a Fullstack Application

    Introduction to MEAN Stack Components

    The MEAN stack consists of MongoDB, Express.js, Angular, and Node.js. It is a popular fullstack JavaScript framework that enables developers to build dynamic web applications efficiently.

    MongoDB

    MongoDB is a NoSQL database that stores data in JSON-like documents. It offers flexibility and scalability, making it ideal for modern applications. Data is structured in collections, which are equivalent to tables in SQL databases.

    
    // Example MongoDB Document
    {
        "name": "John Doe",
        "email": "john.doe@example.com",
        "roles": ["admin", "user"]
    }
            

    Express.js

    Express.js is a lightweight web application framework for Node.js that simplifies building APIs and handling HTTP requests. It serves as the backend server in a MEAN application.

    
    // Basic Express Server Setup
    const express = require('express');
    const app = express();
    const port = 3000;
    
    app.get('/', (req, res) => {
        res.send('Hello World');
    });
    
    app.listen(port, () => {
        console.log(`Server is running on http://localhost:${port}`);
    });
            

    Angular

    Angular is a front-end framework maintained by Google. It enables developers to build dynamic, client-side applications with two-way data binding and dependency injection.

    
    // Basic Angular Component
    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      template: '<h1>Hello Angular</h1>'
    })
    export class AppComponent {}
            

    Node.js

    Node.js is a runtime environment for executing JavaScript code server-side. It acts as the backbone of the MEAN stack, running the Express.js server and interacting with MongoDB.

    Interaction Between Components

    In a MEAN application, the client (Angular) sends HTTP requests to the Express.js server. The server interacts with MongoDB to retrieve or update data and then sends the response back to the client. This seamless integration allows for efficient data management and real-time updates.

  • Implementing Authentication and Authorization in a MEAN Stack Application Using JWT and Angular

    Authentication and Authorization in MEAN Stack

    Implementing authentication and authorization is critical for securing a MEAN stack application. JSON Web Tokens (JWT) are often used to manage secure login and access controls.

    Setting Up JWT in Node.js

    First, install the necessary packages:

    npm install jsonwebtoken bcryptjs

    Then, create a middleware to generate and verify tokens.

    
    // JWT Middleware
    const jwt = require('jsonwebtoken');
    const secret = 'your-secret-key';
    
    function generateToken(user) {
        return jwt.sign({ id: user._id }, secret, { expiresIn: '1h' });
    }
    
    function verifyToken(req, res, next) {
        const token = req.headers['authorization'];
        if (!token) return res.status(403).send('No token provided.');
    
        jwt.verify(token, secret, (err, decoded) => {
            if (err) return res.status(500).send('Failed to authenticate token.');
            req.userId = decoded.id;
            next();
        });
    }
            

    Frontend Implementation in Angular

    In Angular, use services to manage user authentication status and intercept HTTP requests with JWT.

    
    // Auth Service in Angular
    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class AuthService {
      private tokenKey = 'auth-token';
    
      constructor(private http: HttpClient) {}
    
      login(credentials) {
        return this.http.post('/api/login', credentials).subscribe((response: any) => {
          localStorage.setItem(this.tokenKey, response.token);
        });
      }
    
      isAuthenticated() {
        return !!localStorage.getItem(this.tokenKey);
      }
    }
            

    Protecting Routes

    To protect routes in Angular, use route guards to check authentication status.