Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting - HostForLIFE :: Node.js App with User Authentication and Docker Deployment

clock February 12, 2025 07:01 by author Peter

Node.js web application development enables the development of scalable and effective platforms. You will learn how to put up a basic application with a dashboard interface and user authentication in this tutorial. The database will be MongoDB, the web framework will be Express, and the templating will be done with EJS. For simpler deployment, we will also use Docker to containerize our application.

Before you begin, ensure you have the following installed on your system:

  • Node.js and npm
  • Docker
  • Docker Compose
  • A text editor or IDE of your choice

Step 1. Setting Up Your Project
Initialize a New Node.js Project

  • Open your terminal.
  • Create a new directory for your project and navigate into it:


mkdir nodejs-app
cd nodejs-app


Initialize a new Node.js project:
npm init -y

Install Dependencies
Install Express, EJS, Mongoose, and other necessary packages:
npm install express ejs mongoose bcryptjs express-session passport passport-local

Step 2. Create the Application Structure
Create the necessary directories and files for your application:
nodejs-app/

├── app.js
├── Dockerfile
├── docker-compose.yml
├── package.json
├── routes/
│   ├── index.js
│   ├── user.js
├── config/
│   ├── passportConfig.js
├── views/
│   ├── login.ejs
│   ├── register.ejs
│   ├── dashboard.ejs
│   ├── layout.ejs
│   └── partials/
│       └── messages.ejs
├── models/
│   ├── User.js
└── public/
    ├── css/
        ├── style.css


Here is a shell script (create-nodejs-app.sh) to automatically create the directory structure for your Node.js application:
#!/bin/bash

# Define the folder structure
mkdir -p nodejs-app/{routes,config,views,models,public/css}


# Create the necessary files
touch nodejs-app/app.js
touch nodejs-app/Dockerfile
touch nodejs-app/docker-compose.yml
touch nodejs-app/package.json
touch nodejs-app/routes/index.js
touch nodejs-app/routes/user.js
touch nodejs-app/config/passportConfig.js
touch nodejs-app/views/login.ejs
touch nodejs-app/views/register.ejs
touch nodejs-app/views/dashboard.ejs
touch nodejs-app/views/layout.ejs
touch nodejs-app/views/partials/messages.ejs
touch nodejs-app/models/User.js
touch nodejs-app/public/css/style.css

# Confirmation message
echo "Node.js app folder structure created successfully!"


Step 3. Developing the Backend
Set Up Express and Middleware
In app.js, Set up your Express application and middleware to handle requests.

        const express = require('express');
        const mongoose = require('mongoose');
        const session = require('express-session');
        const flash = require('connect-flash');
        const passport = require('passport');
        const app = express();
        const port = 3000;

        // Passport Config
        require('./config/passportConfig')(passport);

        // DB Config
        mongoose.connect('mongodb://mongo:27017/nodejs-app', { useNewUrlParser: true, useUnifiedTopology: true })
            .then(() => console.log('MongoDB Connected'))
            .catch(err => console.log(err));

        // Middleware
        app.use(express.urlencoded({ extended: false }));
        app.use(express.static('public'));

        // EJS
        app.set('view engine', 'ejs');

        // Express Session
        app.use(session({
            secret: 'secret',
            resave: true,
            saveUninitialized: true
        }));

        // Passport middleware
        app.use(passport.initialize());
        app.use(passport.session());

        // Connect Flash
        app.use(flash());

        // Global Variables
        app.use((req, res, next) => {
            res.locals.success_msg = req.flash('success_msg');
            res.locals.error_msg = req.flash('error_msg');
            res.locals.error = req.flash('error');
            next();
        });

        // Routes
        app.use('/', require('./routes/index'));
        app.use('/users', require('./routes/user'));

        // Start Server
        app.listen(port, () => {
            console.log(`Server started on port ${port}`);
        });


Configure Passport for user authentication
Database Models
Use Mongoose to define models in models/User.js.

    const mongoose = require('mongoose');

    const UserSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true
        },
        email: {
            type: String,
            required: true,
            unique: true
        },
        password: {
            type: String,
            required: true
        },
        date: {
            type: Date,
            default: Date.now
        }
    });

    const User = mongoose.model('User', UserSchema);

    module.exports = User;


User Authentication
Implement registration and login functionality in routes/user.js.

     const express = require('express');
    const router = express.Router();
    const bcrypt = require('bcryptjs');
    const passport = require('passport');
    const User = require('../models/User');

    // Register Page
    router.get('/register', (req, res) => res.render('register'));

    // Register Handle
    router.post('/register', (req, res) => {
        const { name, email, password, password2 } = req.body;
        let errors = [];

        // Validation
        if (!name || !email || !password || !password2) {
            errors.push({ msg: 'Please fill in all fields' });
        }

        if (password !== password2) {
            errors.push({ msg: 'Passwords do not match' });
        }

        if (errors.length > 0) {
            res.render('register', { errors, name, email, password, password2 });
        } else {
            User.findOne({ email: email })
                .then(user => {
                    if (user) {
                        errors.push({ msg: 'Email already exists' });
                        res.render('register', { errors, name, email, password, password2 });
                    } else {
                        const newUser = new User({ name, email, password });

                        bcrypt.genSalt(10, (err, salt) => {
                            bcrypt.hash(newUser.password, salt, (err, hash) => {
                                if (err) throw err;
                                newUser.password = hash;
                                newUser.save()
                                    .then(user => {
                                        req.flash('success_msg', 'You are now registered and can log in');
                                        res.redirect('/users/login');
                                    })
                                    .catch(err => console.log(err));
                            });
                        });
                    }
                });
        }
    });

    // Login Page
    router.get('/login', (req, res) => res.render('login'));

    // Login Handle
    router.post('/login', (req, res, next) => {
        passport.authenticate('local', {
            successRedirect: '/dashboard',
            failureRedirect: '/users/login',
            failureFlash: true
        })(req, res, next);
    });

    // Logout Handle
    router.get('/logout', (req, res) => {
        req.logout(() => {
            req.flash('success_msg', 'You are logged out');
            res.redirect('/users/login');
        });
    });

    module.exports = router;


Utilize Passport for handling authentication. config/passportConfig.js
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

// Load User model
const User = require('../models/User');

module.exports = function (passport) {
    passport.use(new LocalStrategy({ usernameField: 'email' }, (email, password, done) => {
        User.findOne({ email: email })
            .then(user => {
                if (!user) {
                    return done(null, false, { message: 'That email is not registered' });
                }

                bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) throw err;
                    if (isMatch) {
                        return done(null, user);
                    } else {
                        return done(null, false, { message: 'Password incorrect' });
                    }
                });
            })
            .catch(err => console.log(err));
    }));

    passport.serializeUser((user, done) => {
        done(null, user.id);
    });

    passport.deserializeUser((id, done) => {
        User.findById(id, (err, user) => {
            done(err, user);
        });
    });
};


routes/user.js
const express = require('express');
const router = express.Router();
const { ensureAuthenticated } = require('../config/auth');

// Welcome Page
router.get('/', (req, res) => res.render('welcome'));

// Dashboard Page
router.get('/dashboard', ensureAuthenticated, (req, res) =>
    res.render('dashboard', {
        user: req.user
    })
);

module.exports = router;


config/auth.js
module.exports = {
    ensureAuthenticated: function (req, res, next) {
        if (req.isAuthenticated()) {
            return next();
        }
        req.flash('error_msg', 'Please log in to view this resource');
        res.redirect('/users/login');
    }
};


Step 4. Creating the Frontend
EJS Templates
Create views for registration, login, and the dashboard in the views/ directory.
views/register.ejs

        <%- include('layout') %>
        <form action="/users/register" method="POST">
            <div class="form-group">
                <input type="text" name="name" class="form-control" placeholder="Name">
            </div>
            <div class="form-group">
                <input type="email" name="email" class="form-control" placeholder="Email">
            </div>
            <div class="form-group">
                <input type="password" name="password" class="form-control" placeholder="Password">
            </div>
            <div class="form-group">
                <input type="password" name="password2" class="form-control" placeholder="Confirm Password">
            </div>
            <button type="submit" class="btn btn-primary">Register</button>
        </form>


views/login.ejs
<%- include('layout') %>
<form action="/users/login" method="POST">
    <div class="form-group">
        <input type="email" name="email" class="form-control" placeholder="Email">
    </div>
    <div class="form-group">
        <input type="password" name="password" class="form-control" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>


views/dashboard.ejs
<%- include('layout') %>
<h1>Welcome, <%= user.name %>!</h1>
<a href="/users/logout" class="btn btn-danger">Logout</a>

JavaScript
views/layout.ejs
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Node.js App</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <nav>
        <a href="/">Home</a>
        <a href="/users/login">Login</a>
        <a href="/users/register">Register</a>
    </nav>
    <div class="container">
        <%- include('partials/messages') %>
    </div>
</body>
</html>


Create the partials Directory and messages.ejs
Inside your views directory, create a new folder called partials.
Inside this partials folder, create a file called messages.ejs.

Here is an example of the content for messages.ejs:
    <% if (typeof success_msg != 'undefined') { %>
        <div class="alert alert-success">
            <%= success_msg %>
        </div>
    <% } %>

    <% if (typeof error_msg != 'undefined') { %>
        <div class="alert alert-danger">
            <%= error_msg %>
        </div>
    <% } %>

    <% if (typeof errors != 'undefined' && errors.length > 0) { %>
        <div class="alert alert-danger">
            <ul>
            <% errors.forEach(function(error) { %>
                <li><%= error.msg %></li>
            <% }) %>
            </ul>
        </div>
    <% } %>


Static Files
Style your application using CSS in the public/css/style.css file.

    /* Reset some default browser styles */
    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: Arial, sans-serif;
        background-color: #f4f4f4;
        color: #333;
        line-height: 1.6;
        margin: 0;
        padding: 0;
    }

    /* Container */
    .container {
        max-width: 1170px;
        margin: 0 auto;
        padding: 20px;
    }

    /* Navigation */
    nav {
        background: #333;
        color: #fff;
        padding: 15px;
        text-align: center;
    }

    nav a {
        color: #fff;
        text-decoration: none;
        margin: 0 10px;
    }

    nav a:hover {
        text-decoration: underline;
    }

    /* Form Styling */
    form {
        background: #fff;
        padding: 20px;
        margin-top: 20px;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }

    .form-group {
        margin-bottom: 15px;
    }

    .form-group input {
        width: 100%;
        padding: 10px;
        border: 1px solid #ccc;
        border-radius: 5px;
    }

    button {
        background: #333;
        color: #fff;
        border: 0;
        padding: 10px 15px;
        cursor: pointer;
        border-radius: 5px;
    }

    button:hover {
        background: #555;
    }

    /* Messages */
    .alert {
        padding: 10px;
        background-color: #f4f4f4;
        color: #333;
        margin-bottom: 20px;
        border: 1px solid #ccc;
    }

    .alert-success {
        background-color: #dff0d8;
        color: #3c763d;
    }

    .alert-error {
        background-color: #f2dede;
        color: #a94442;
    }

    /* Dashboard */
    h1 {
        font-size: 24px;
        margin-bottom: 20px;
    }

    .btn-danger {
        background-color: #e74c3c;
    }

    .btn-danger:hover {
        background-color: #c0392b;
    }


Step 5. Dockerizing the Application

    Dockerfile
        Create a Dockerfile to specify the build process for your application.

        FROM node:16

        WORKDIR /app

        COPY package*.json ./

        RUN npm install

        COPY . .

        EXPOSE 3000

        CMD ["node", "app.js"]


Docker Compose
Define services, including your Node.js app and MongoDB, in docker-compose.yml.

    version: '3'
    services:
      app:
        build: .
        ports:
          - "3000:3000"
        depends_on:
          - mongo
      mongo:
        image: mongo
        ports:
          - "27017:27017"


Step 6. Running Your Application
Build and Run with Docker Compose

docker-compose up --build


Access the App: Go to http://localhost:3000 in your browser.

Access the App: Go to http://localhost:3000 in your browser.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



AngularJS Hosting Europe - HostForLIFE :: Function-Based Interceptor in Angular

clock February 5, 2025 06:09 by author Peter

An excellent method for managing and altering HTTP requests and answers across your application is to use Angular interceptors. Although classes are typically used to build interceptors, function-based interceptors can be used for more straightforward and reusable code.


We'll go over how to make and use function-based interceptors in Angular in this blog, along with simple examples for increased flexibility and clarity.

What is a function-based Interceptor?
A function-based interceptor is a simpler and more flexible option compared to a class-based interceptor. Instead of creating a whole class with an intercept method, you put your logic into individual functions. This approach helps with,

  • Separation of Concerns: Smaller, focused functions are easier to test and maintain.
  • Reusability: You can reuse the interceptor logic by sharing or combining multiple functions.

Benefits of Function-Based Interceptors

  • Less Setup: You only need a function, not an entire class.
  • Easier Testing: It’s simpler to test individual functions.
  • Flexible: You can combine several functions to handle complex request/response processes.

How to implement a function-based Interceptor?
Let us create an angular project with the imported HttpClientModule.
    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    import { AppComponent } from './app.component';

    @NgModule({
      declarations: [AppComponent],
      imports: [BrowserModule, HttpClientModule],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

TypeScript
Create a function-based interceptor - a function-based interceptor works by using a factory to handle the request/response logic.

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

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  console.log('Intercepting Request:', req);

  // Add an Authorization header
  const token = 'your-token-here';
  const clonedRequest = req.clone({
    setHeaders: {
      Authorization: `Bearer ${token}`,
    },
  });

  console.log('Modified Request:', clonedRequest);

  // Forward the modified request
  return next(clonedRequest);
};


Key Points

  • Factory Function: Use HttpInterceptorFn to define the interceptor.
  • Modify Request: Use req.clone() to create a modified version of the request.
  • Forward Request: Send the cloned request to the next step with next.

Register the Function Interceptor
To register the function-based interceptor, use the provided HTTP client configuration in your AppModule or feature module.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, provideHttpClient, withInterceptors } from '@angular/common/http';
import { authInterceptor } from './auth-interceptor.fn';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [
    provideHttpClient(withInterceptors([authInterceptor]))
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Why Use provideHttpClient?
Introduced in Angular 15, this modern API makes it easier to configure the HTTP client and supports function-based interceptors directly.

Use the Interceptor in an HTTP Request

Now that the interceptor is registered test it by making an HTTP request.
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'function-based-Interceptor';

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe((data) => {
      console.log('Response:', data);
    });
  }
}


Let us execute the app and validate whether the interceptor was properly executed.



AngularJS Hosting Europe - HostForLIFE :: Understanding the Angular Lifecycle Hooks

clock January 22, 2025 08:17 by author Peter

In Angular, components go through a series of stages from their creation to destruction. These stages are collectively known as the Angular lifecycle. Understanding the lifecycle hooks provided by Angular allows developers to tap into key moments in a component's lifecycle to perform initialization, cleanup, and other crucial operations. This article provides an in-depth look at each of these lifecycle hooks and how to use them effectively.

Angular Lifecycle Hooks
Here is a list of the primary lifecycle hooks in Angular.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

Let's explore each of these hooks in detail.

1. ngOnChanges

When it’s called: This hook is called whenever an input property bound to a component changes. It’s called before ngOnInit and whenever the input properties are updated.
Use case: Use ngOnChanges to act on changes to input properties from the parent component.

Example
import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
@Component({
  selector: 'app-child',
  template: '<p>{{data}}</p>',
})
export class ChildComponent implements OnChanges {
  @Input() data: string;
  ngOnChanges(changes: SimpleChanges) {
    console.log('ngOnChanges called', changes);
  }
}


2. ngOnInit
When it’s called: This hook is called once, after the first ngOnChanges. It’s typically used for component initialization.
Use case: Use ngOnInit to perform component initialization, like fetching data.

Example
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-example',
  template: '<p>Example works!</p>',
})
export class ExampleComponent implements OnInit {
  ngOnInit() {
    console.log('ngOnInit called');
  }
}


3. ngDoCheck
When it’s called: This hook is called during every change detection run. It’s useful for custom change detection.
Use case: Use ngDoCheck to implement custom change detection logic.

Example
import { Component, DoCheck } from '@angular/core';
@Component({
  selector: 'app-check',
  template: '<p>Check works!</p>',
})
export class CheckComponent implements DoCheck {
  ngDoCheck() {
    console.log('ngDoCheck called');
  }
}


4. ngAfterContentInit
When it’s called: This hook is called after Angular projects external content into the component’s view (ng-content).
Use case: Use ngAfterContentInit to respond to content projection into the component.

Example
import { Component, AfterContentInit } from '@angular/core';
@Component({
  selector: 'app-content',
  template: '<ng-content></ng-content>',
})
export class ContentComponent implements AfterContentInit {
  ngAfterContentInit() {
    console.log('ngAfterContentInit called');
  }
}


5. ngAfterContentChecked
When it’s called: This hook is called after every check of the component’s projected content.
Use case: Use ngAfterContentChecked to act after the content is checked.

Example
import { Component, AfterContentChecked } from '@angular/core';
@Component({
  selector: 'app-content-check',
  template: '<ng-content></ng-content>',
})
export class ContentCheckComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    console.log('ngAfterContentChecked called');
  }
}


6. ngAfterViewInit
When it’s called: This hook is called after Angular initializes the component’s views and child views.
Use case: Use ngAfterViewInit to perform actions after the component’s view is initialized.

Example
import { Component, AfterViewInit } from '@angular/core';
@Component({
  selector: 'app-view-init',
  template: '<p>View Init works!</p>',
})
export class ViewInitComponent implements AfterViewInit {
  ngAfterViewInit() {
    console.log('ngAfterViewInit called');
  }
}


7. ngAfterViewChecked
When it’s called: This hook is called after every check of the component’s view.
Use case: Use ngAfterViewChecked to act after the component’s view is checked.

Example
import { Component, AfterViewChecked } from '@angular/core';
@Component({
  selector: 'app-view-check',
  template: '<p>View Check works!</p>',
})
export class ViewCheckComponent implements AfterViewChecked {
  ngAfterViewChecked() {
    console.log('ngAfterViewChecked called');
  }
}

8. ngOnDestroy
When it’s called: This hook is called just before Angular destroys the component.
Use case: Use ngOnDestroy for cleanup, like unsubscribing from observables and detaching event handlers.

Example
import { Component, OnDestroy } from '@angular/core';
@Component({
  selector: 'app-destroy',
  template: '<p>Destroy works!</p>',
})
export class DestroyComponent implements OnDestroy {
  ngOnDestroy() {
    console.log('ngOnDestroy called');
  }
}

Lifecycle Sequence
Understanding the order of these hooks is crucial for correctly implementing logic that depends on the component's lifecycle stages.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy

Practical Use Cases

  • ngOnInit: Ideal for initialization tasks like fetching data from a service.
  • ngOnChanges: Useful for reacting to changes in input properties.
  • ngOnDestroy: Perfect for cleaning up resources, like unsubscribing from observables.
  • ngAfterViewInit: Great for manipulating the DOM after the view is initialized.

Conclusion
Mastering Angular lifecycle hooks is essential for building robust and maintainable Angular applications. By understanding when and how to use each hook, developers can ensure their components are properly initialized, updated, and cleaned up. This not only leads to better performance but also improves code organization and readability.



European Visual Studio 2022 Hosting - HostForLIFE :: Use Endpoints Explorer with .http Files in Visual Studio

clock January 17, 2025 07:07 by author Peter

Through the integration of Endpoints Explorer, a potent tool that functions flawlessly with.http files, Visual Studio 2022 has completely transformed API testing. This combination removes the need for third-party tools like Postman or Swagger by enabling developers to design, administer, and run API tests straight from the IDE.

With Endpoints Explorer, developers enjoy.

  • Reduced Context Switching
  • Increased Productivity
  • Streamlined API Testing Workflow

What Problem Does It Solve?
Before this feature, developers relied heavily on external tools to test their APIs. This involved.

  • Exporting endpoints or configurations manually.
  • Managing additional setups outside their IDE.

Endpoints Explorer fixes this by embedding API testing into Visual Studio, making the process smooth and time-efficient.

How to use Endpoints Explorer?
Open Your Project

Ensure you are using Visual Studio 2022 version 17.6 or later and load your project.

Access Endpoints Explorer
Navigate to View -> Other Windows -> Endpoints Explorer.


This tool scans your project for,

  • Controllers marked with the [ApiController] attribute.
  • Minimal API configurations.

You’ll see a comprehensive list of all available endpoints.

Working with Endpoints
Right-clicking an endpoint in the explorer provides two options.

Option 1. Open in Editor
This opens the corresponding controller or minimal API definition in the code editor. Perfect for quick reviews and edits.

Option 2. Generate Request
Selecting this option generates an API request in a .http file, enabling you to test the endpoint directly in Visual Studio.

Working with .http Files

  • If a .HTTP file (named after your project) exists, a new request is added to it.
  • Otherwise, a new .http file is created automatically.

Writing and Sending HTTP Requests
The .HTTP file is where you create and send requests. It supports:

  • GET, POST, PUT, DELETE requests.
  • Custom headers, query parameters, and JSON payloads.

Here’s an example of a request.
### Fetch all users
GET https://your-api-url.com/users
Authorization: Bearer YOUR-TOKEN

### Add a user
POST https://your-api-url.com/users
Content-Type: application/json

{
"name": "John Doe",
"email": "[email protected]"
}

Benefits of Endpoints Explorer + .http File Combo

  • All-in-One Workflow: No need to switch between IDE and external tools like Postman.
  • Collaboration Made Easy: Share .HTTP files with your team as part of your repository for consistent API testing.
  • Integrated Experience: Quickly debug endpoints and iterate through development with minimal disruptions.
  • Simpler Configuration: Directly test APIs without exporting Postman collections or Swagger setups.

Best Practices for Using Endpoints Explorer

  • Organize Requests: Group your .http requests by features or endpoints to keep your testing structured.
  • Leverage Comments: Add meaningful comments in .HTTP files to describe each request.
  • Commit .http Files to Source Control: Share and track changes with your team to maintain consistency.

Conclusion
Visual Studio 2022 revolutionizes API testing by providing developers with a quicker, more effective workflow with the use of Endpoints Explorer and.http files. For more productivity, embrace the integrated experience and bid adieu to extraneous tools. All set to give it a try? Upgrade to Visual Studio 2022 (version 17.6 or above) and start exploring the world of smooth API testing right now! Do you know how to use Endpoints Explorer? Tell us about your experience in the space provided here.



AngularJS Hosting Europe - HostForLIFE :: Configure Build Environments With Angular

clock January 10, 2025 06:47 by author Peter

Configuring build environments in Angular is essential for managing different settings and configurations for development, staging, production, or any other environments. Angular provides a built-in mechanism for this via the angular.json file and the environments folder.


Here are steps to configure build environments in an Angular application.

Step 1. Create project
ng new my-angular-app

Step 2. Create Environment Files
Angular typically comes with two environment files out of the box.
src/environments/environment.ts (for development)
src/environments/environment.prod.ts (for production)

You can create additional files for other environments (e.g., staging).

Each file exports an object with environment-specific properties.
// environment.ts (development)
export const environment = {
  production: false,
  apiBaseUrl: 'http://localhost:4000/api',
};

// environment.prod.ts (production)
export const environment = {
  production: true,
  apiBaseUrl: 'https://api.example.com',
};

// environment.staging.ts (staging)
export const environment = {
  production: false,
  apiBaseUrl: 'https://staging-api.example.com',
};


Step 3. Configure File Replacements
Modify the angular.json file to specify file replacements for different build configurations.

Locate the fileReplacements section under the configurations key in your Angular project.
"configurations": {
  "production": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.prod.ts"
      }
    ]
  },
  "staging": {
    "fileReplacements": [
      {
        "replace": "src/environments/environment.ts",
        "with": "src/environments/environment.staging.ts"
      }
    ]
  }
}


Step 4. Add Build Scripts
Update the angular.json file to define build configurations for new environments.
"architect": {
  "build": {
    "configurations": {
      "production": {
        ...
      },
      "staging": {
        "fileReplacements": [
          {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.staging.ts"
          }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "buildOptimizer": true,
        "budgets": [
          {
            "type": "initial",
            "maximumWarning": "2mb",
            "maximumError": "5mb"
          }
        ]
      }
    }
  }
}

Step 5. Build for Specific Environments
Use the --configuration flag to build for specific environments.
ng build --configuration=staging
ng build --configuration=production


For development, the default build configuration applies unless overridden.

Step 6. Use Environment Variables in Code
In your Angular code, use the environment object to access environment-specific values.
import { environment } from '../environments/environment';
console.log('API Base URL:', environment.apiBaseUrl);
if (environment.production) {
  console.log('Running in production mode');
}


Step 7. Add Additional Settings
For complex builds, you can.

  • Use environment variables with tools like dotenv for dynamic replacements.
  • Integrate third-party CI/CD tools to manage deployment-specific configurations.

By following these steps, you can manage multiple build environments efficiently in your Angular application. Let me know if you'd like further assistance or an example.



AngularJS Hosting Europe - HostForLIFE :: TypeScript command 'tsc' not running in Terminal and PowerShell

clock December 17, 2024 06:08 by author Peter

When we run a typescript version checking command,
tsc -v

We may get error in either PowerShell prompt or Visual Studio or VS Code terminal, such as

However, if we run this same command from a command line prompt, such as Windows Colose, we can get the result:

We can see something like this

There are some articles to discuss this issue, but most of them went to a wrong answer. Actually, it is not true. From the PowerShell window, we can see:

The execution policy isn't a security system that restricts user actions. For example, users can easily bypass a policy by typing the script contents at the command line when they cannot run a script. Instead, the execution policy helps users to set basic rules and prevents them from violating them unintentionally.

Such as

The default for local Machine is Restricted

That is the reason that we cannot run the 'tsc' command from PowerShell or Visual studio and VS code terminal.

How to Fix?
Set it to ByPass:

You must be an admin role when opening the prompt:

Or



AngularJS Hosting Europe - HostForLIFE :: Connecting Angular Frontend to MongoDB via Express Backend

clock December 9, 2024 06:32 by author Peter

MongoDB With Angular Sample
Connecting MongoDB with an Express backend and an Angular frontend involves several steps. Here's a detailed guide, including a code sample, input/output, and steps.

Step 1. Set Up MongoDB
Install MongoDB

  • Install MongoDB locally or use a cloud solution like MongoDB Atlas.
  • Start the MongoDB server.

Create a Database

  • Use the MongoDB shell or a GUI tool like MongoDB Compass to create a database, e.g., my_database.
  • Add a collection, e.g., users.

Step 2. Create an Express Backend
Initialize the Project
mkdir express-mongodb-app
cd express-mongodb-app
npm init -y
npm install express mongoose body-parser cors


Create the Server File: Create a file named server.js.
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();

// Middleware
app.use(cors());
app.use(bodyParser.json());

// MongoDB Connection
mongoose.connect('mongodb://localhost:27017/my_database', {
    useNewUrlParser: true,
    useUnifiedTopology: true,
}).then(() => console.log("MongoDB connected"))
  .catch(err => console.error(err));

// Define Schema and Model
const userSchema = new mongoose.Schema({
    name: String,
    email: String,
});
const User = mongoose.model('User', userSchema);
// Routes
app.get('/api/users', async (req, res) => {
    const users = await User.find();
    res.json(users);
});
app.post('/api/users', async (req, res) => {
    const newUser = new User(req.body);
    await newUser.save();
    res.status(201).json(newUser);
});
// Start Server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
});

Run the Server
node server.js

Step 3. Create the Angular Frontend

Set Up Angular Project
ng new angular-mongodb-app
cd angular-mongodb-app
ng add @angular/material
npm install axios

Service for API Communication: Create a file src/app/services/user.service.ts.
import { Injectable } from '@angular/core';
import axios from 'axios';
@Injectable({
    providedIn: 'root'
})
export class UserService {
    private baseUrl = 'http://localhost:3000/api/users';
    getUsers() {
        return axios.get(this.baseUrl);
    }
    addUser(user: { name: string; email: string }) {
        return axios.post(this.baseUrl, user);
    }
}


Component for User Interaction: Update src/app/app.component.ts.

typescript

import { Component, OnInit } from '@angular/core';
import { UserService } from './services/user.service';

@Component({
    selector: 'app-root',
    template: `
        <div style="text-align: center;">
            <h1>Angular with Express & MongoDB</h1>
            <form (submit)="addUser($event)">
                <input type="text" [(ngModel)]="name" placeholder="Name" name="name" required>
                <input type="email" [(ngModel)]="email" placeholder="Email" name="email" required>
                <button type="submit">Add User</button>
            </form>
            <ul>
                <li *ngFor="let user of users">{{ user.name }} ({{ user.email }})</li>
            </ul>
        </div>
    `,
    styles: []
})
export class AppComponent implements OnInit {
    users: any[] = [];
    name = '';
    email = '';

    constructor(private userService: UserService) {}

    ngOnInit() {
        this.loadUsers();
    }

    async loadUsers() {
        const response = await this.userService.getUsers();
        this.users = response.data;
    }

    async addUser(event: Event) {
        event.preventDefault();
        await this.userService.addUser({ name: this.name, email: this.email });
        this.loadUsers();
        this.name = '';
        this.email = '';
    }
}


Install Angular Forms Module: Add FormsModule to AppModule.
typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule {}


Run the Angular Application
ng serve

Step 4. Input and Output
Input

Fill the form with a name and email, e.g.
Name: "Peter Scott"
Email: "[email protected]"

Output: The list below the form will update to include the newly added user.

less
Peter Scott ([email protected])

Step 5. Visual Workflow (Images)
Backend (server.js)

  • Database schema for storing user data.
  • APIs (/api/users) for CRUD operations.


Frontend (Angular App)

  • The user fills out the form.
  • Data is sent to the Express backend.
  • Data is saved in MongoDB.
  • Users are displayed dynamically.


AngularJS Hosting Europe - HostForLIFE :: Convert Doc to Pdf using NodeJS

clock December 5, 2024 08:53 by author Peter

To convert a DOC file to PDF using Node.js and PowerShell, you can use the following steps:
Install the ‘child_process’ package in your Node.js project by running the following command in your project’s terminal:

npm i child_process

Create a PowerShell script that converts the DOC file to PDF using Microsoft Word. You can use the following script:
$documents_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net.docx'
$output_path = 'C:\Users\Peter\Downloads\DoctoPdf\doc\Web_Service_Uing_Ajax_in_net12.pdf'
$word_app = New-Object -ComObject Word.Application
# This filter will find .doc as well as .docx documents
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
    $document = $word_app.Documents.Open($_.FullName)
    $pdf_filename =  "$output_path"
    $document.SaveAs($pdf_filename)
    $document.Close()
}
$word_app.Quit()
return $output_path

Make sure to replace the input and output file paths with the actual paths to your files.
Use the ‘child_process’ package in your Node.js code to execute the PowerShell script. You can use the following code:
    const express =  require('express');
    const app =  express();
    const port = 5000;
    const { exec } = require('child_process');
    const { v4: uuidv4 } = require('uuid');
    const fileUpload = require('express-fileupload');
    const fs = require('fs');
    app.use(express.json({
        limit: "200mb"
      }));
      app.use(
        express.urlencoded({
          extended: true,
          limit: "200mb",
        })
      );


    app.use(fileUpload());

    app.post('/', function(req, res,next){
        console.log('req', req.files.inputfile)

        let uploaded_path = __dirname+'/doc/' + req.files.inputfile.name;
        fs.writeFile(uploaded_path, req.files.inputfile.data, function(err) {
            if(err) {
                return console.log(err);
            }
            ///console.log("The file was saved!");
            const cmd = `$documents_path = "${uploaded_path}"
            $output_path = '${__dirname}/doc/${uuidv4()}.pdf'
            $word_app = New-Object -ComObject Word.Application
            # This filter will find .doc as well as .docx documents
            Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
                $document = $word_app.Documents.Open($_.FullName)
                $pdf_filename = "$output_path"
                $document.SaveAs([ref] $pdf_filename, [ref] 17)
                $document.Close()
            }
            $word_app.Quit()
            return $output_path`;
            exec(cmd, {'shell':'powershell.exe'}, (error, stdout, stderr)=> {
                console.log('Error', stderr)
                   console.log('OUTPUT', stdout);
                   res.status(200).json({status:200, msg:"success", stdout: stdout})
            })
        });

    })


    app.listen(port, function(){
        console.log('Server is running on port', port);
    })


Make sure to replace the script path and input file path with the actual paths to your files.
Run your Node.js code and the DOC file will be converted to PDF using PowerShell. The output PDF file will be saved to the path specified in the PowerShell script.



AngularJS Hosting Europe - HostForLIFE :: How Can I Use the Angular 18 Component to Call a JavaScript Function?

clock November 29, 2024 08:39 by author Peter

In this walk, you will learn about running and calling javascript functions from the Angular component.

How it’s implemented and what is the description?

  • Create Angular project - AnguWalk.
  • Run the application and check that the project was created successfully.
  • Create JS file with function.
  • Adding JS file link/reference to angular.json
  • Component (TS file) coding.
  • Execute the Project
  • Output

Create an Angular Project called “AnguWalk” using the following CLI command.Commandng new AnguWalkBashExample

Go inside the project folder and open the Visual Studio code.

Command
cd anguwalk
<enter>
code .
<enter>

Example

Note. Visual Studio code will get started only if your system is configured with path and settings.

Create Javascript file

  • First, create a JS folder inside the SRC folder.
  • Right-click on SRC and select the option New Folder.

    function HelloMsg(arg) {
        alert("Welcome to Angular Class - " + arg);
    }

Reference JS File in angular.json file
The Angular.json file is located inside the project root folder. Open and update the SCRIPTS array which is inside the builds object.

"scripts": [
    "src/js/WelcomeMsg.js"
]


Open app.component.html and update the code.

Note. Remove the default code of app.component.html.
import { Component, OnInit } from '@angular/core';
import { RouterOutlet } from '@angular/router';

declare function HelloMsg(arg: any): void;

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  ngOnInit() {
    HelloMsg("Peter, Scott");
  }

  title = 'AnguWalk';
}

Now, run the project to check the output.

Command
ng serve --open

Output


You see the javascript HelloMsg function executed and the alert window displayed successfully. Happy Coding!



AngularJS Hosting Europe - HostForLIFE :: Debugging Angular Using Visual Studio Code

clock November 12, 2024 06:06 by author Peter

This brief post is meant for readers who are using Visual Studio Code to work on an Angular project and are having trouble adding a debugger. When I first started using Visual Studio Code to debug Angular projects, I thought it was rather strange, but eventually I thought it was cool. I discovered that many users were asking how to debug an Angular project in Visual Studio Code. I therefore considered composing this brief piece.

Note: I created and executed my Angular project, which internally uses WebPack, using the Angular CLI.

Step by Step add debugger in Visual Studio Code
Open your Angular project in Visual Studio Code.

Install Extension, as shown below.

Click Debug icon & Add Configuration, as shown below.

Select Chrome and add the configuration given below in launch.json file (This file gets created in .vscode folder).
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Launch Chrome against localhost",
            "type": "chrome",
            "request": "launch",
            "url": "http://localhost:4200",
            "sourceMaps": true,
            "webRoot": "${workspaceRoot}",
            "sourceMapPathOverrides": {
                "webpack:///./*": "${workspaceRoot}/*"
            }
        }
    ]
}

Open command terminal. As I am using Angular CLI to run my Angular project. I am using
> ng serve
command to build and run my application. By default, it runs on port 4200 (Same port is mentioned in my launch.json file).

Now, your development Server is running. Now, you can press F5 or play icon in the debug tab. Keep the break point and it will hit the .ts file.

Note.You may be surprised how JS can map my .ts file in code and debugger can hit my .ts file. This is because of "sourceMaps": true setting in launch.json. Similarly, we can add more debugger by adding an extension and then configuring in same launch.json file. I hope, this small article will be helpful to you. Please do comment, whether it’s good or bad. Sharing is valuable. Thank you for reading and have a great day.



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in