Are you looking to create a login registration system with Angular, NodeJS, and MongoDB? Look no further! This article will provide you with a comprehensive guide to creating your own login registration system. We will cover everything from setting up your development environment to building a complete login registration system using Angular, NodeJS, and MongoDB.
1. Introduction
Login registration systems are a common feature of web applications. They allow users to create an account, log in, and access the application’s features. In this article, we will build a login registration system using Angular, NodeJS, and MongoDB. Angular is a popular frontend framework for building web applications, while NodeJS is a powerful backend technology that enables server-side development. MongoDB is a NoSQL database that is scalable and flexible, making it a popular choice for modern web applications.
2. Setting up the Development Environment
Before we can start building our login registration system, we need to set up our development environment. This involves installing NodeJS, Angular CLI, and MongoDB.
2.1 Installing NodeJS
NodeJS is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It allows us to run JavaScript code on the server-side. To install NodeJS, follow these steps:
- Go to the NodeJS website (https://nodejs.org) and download the latest version.
- Run the installer and follow the prompts.
2.2 Installing Angular CLI
Angular CLI is a command-line interface for Angular. It provides a set of tools and commands for creating, building, and testing Angular applications. To install Angular CLI, follow these steps:
- Open a command prompt or terminal window.
- Run the following command: npm install -g @angular/cli
- Wait for the installation to complete.
2.3 Installing MongoDB
MongoDB is a NoSQL database that stores data in a JSON-like format. It is scalable, flexible, and easy to use. To install MongoDB, follow these steps:
- Go to the MongoDB website (https://www.mongodb.com) and download the latest version.
- Run the installer and follow the prompts.
3. Creating the Backend with NodeJS and MongoDB
Now that we have set up our development environment, we can start creating the backend of our login registration system. We will use NodeJS and MongoDB for this.
3.1 Setting up the Backend Project
To create our backend project, follow these steps:
- Open a command prompt or terminal window.
- Navigate to the directory where you want to create your project.
- Run the following command: mkdir backend && cd backend
- Run the following command: npm init -y
- Run the following command: npm install express mongoose cors
3.2 Creating the User Schema
We will create a User schema to store user information in the database. To create the User schema, follow these steps:
- In the backend directory, create a new file called models/User.js.
- In User.js, add the following code:
const mongoose = require('mongoose'); const UserSchema = mongoose.Schema({ username: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true } }); module.exports = mongoose.model('User', UserSchema);
This creates a new schema for the User model, with fields for username, email, and password.
3.3 Creating the User Routes
Next, we will create the routes for the User model, which will handle requests from the frontend. To create the User routes, follow these steps:
- In the backend directory, create a new file called routes/user.js.
- In user.js, add the following code:
const express = require('express'); const router = express.Router(); const User = require('../models/User'); router.post('/register', (req, res) => { const newUser = new User({ username: req.body.username, email: req.body.email, password: req.body.password }); newUser.save() .then(() => res.json('User added!')) .catch(err => res.status(400).json('Error: ' + err)); }); router.post('/login', (req, res) => { User.findOne({ email: req.body.email, password: req.body.password }) .then(user => { if (user) { res.json('Login successful!'); } else { res.status(400).json('Invalid email or password.'); } }) .catch(err => res.status(400).json('Error: ' + err)); }); module.exports = router;
This creates two routes for the User model – /register for registering a new user, and /login for logging in an existing user.
4. Creating the Frontend with Angular
Now that we have our backend set up, we can start creating the frontend of our login registration system. We will use Angular for this.
4.1 Setting up the Frontend Project
To create our frontend project, follow these steps:
- Open a command prompt or terminal window.
- Navigate to the directory where you want to create your project.
- Run the following command: ng new frontend
- Wait for the installation to complete.
4.2 Creating the Login Component
We will create a Login component to handle user login. To create the Login component, follow these steps:
- In the frontend directory, run the following command: ng generate component login
- Open login.component.html and replace the existing code with the following:
- Add the following code below the form:
<div class="container"> <h2>Login</h2> <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" [(ngModel)]="email" name="email"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" [(ngModel)]="password" name="password"> </div> <button type="submit" class="btn btn-primary">Login</button> </form> <div *ngIf="message" class="alert alert-danger">{{ message }}</div> </div>
This code creates a form with input fields for the email and password, and a submit button. It also displays an error message if the login fails.
- Open login.component.ts and replace the existing code with the following:
import { Component } from '@angular/core'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent { email: string; password: string; message: string; constructor(private authService: AuthService) {} onSubmit() { this.authService.login(this.email, this.password) .subscribe( data => { console.log(data); this.message = 'Login successful!'; }, error => { console.log(error); this.message = 'Invalid email or password.'; }); } }
This code imports the AuthService and creates a LoginComponent class with properties for the email, password, and error message. It also defines an onSubmit() method that calls the AuthService to log in the user and displays the appropriate message.
4.3 Creating the Registration Component
We will create a Registration component to handle user registration. To create the Registration component, follow these steps:
- In the frontend directory, run the following command: ng generate component registration
- Open registration.component.html and replace the existing code with the following:
<div class="container"> <h2>Registration</h2> <form (ngSubmit)="onSubmit()"> <div class="form-group"> <label>Username</label> <input type="text" class="form-control" [(ngModel)]="username" name="username"> </div> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" [(ngModel)]="email" name="email"> </div> <div class="form-group"> <label>Password</label> <input type="password" class="form-control" [(ngModel)]="password" name="password"> </div> <button type="submit" class="btn btn-primary">Register</button> </form> <div *ngIf="message" class="alert alert-danger">{{ message }}</div> </div>
This code creates a form with input fields for the username, email, password, and a submit button. It also displays an error message if the registration fails.
- Open registration.component.ts and replace the existing code with the following:
import { Component } from '@angular/core'; import { AuthService } from '../auth.service'; @Component({ selector: 'app-registration', templateUrl: './registration.component.html', styleUrls: ['./registration.component.css'] }) export class RegistrationComponent { username: string; email: string; password: string; message: string; constructor(private authService: AuthService) {} onSubmit() { this.authService.register(this.username, this.email, this.password) .subscribe( data => { console.log(data); this.message = 'Registration successful!'; }, error => { console.log(error); this.message = 'Something Wrong.'; }); } }
This code imports the AuthService and creates a RegistrationComponent class with properties for the username, email, password, and error message. It also defines an onSubmit() method that calls the AuthService to register the user and displays the appropriate message.
4.4 Creating the Auth Service
We will now create an AuthService to handle authentication and registration. To create the AuthService, follow these steps:
- In the frontend directory, run the following command: ng generate service auth
- Open auth.service.ts and replace the existing code with the following:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class AuthService { private baseURL = 'http://localhost:3000'; constructor(private http: HttpClient) {} register(username: string, email: string, password: string) { return this.http.post(`${this.baseURL}/register`, { username, email, password }); } login(email: string, password: string) { return this.http.post(`${this.baseURL}/login`, { email, password }); } }
This code imports the HttpClient and creates an AuthService class with methods for registration and login. It also defines a baseURL property to point to the backend API.
4.5 Creating the Backend API
Now, we will create a Node.js backend API to handle authentication and registration. To create the backend API, follow these steps:
- In the root directory, create a new file named server.js with the following code:
const express = require('express'); const bodyParser = require('body-parser'); const cors = require('cors'); const mongoose = require('mongoose'); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const app = express(); app.use(bodyParser.json()); app.use(cors()); mongoose.connect('mongodb://localhost:27017/login-registration', { useNewUrlParser: true }); const User = mongoose.model('User', { username: String, email: String, passwordHash: String }); function generateAccessToken(user) { return jwt.sign(user, 'secret'); } app.post('/register', async (req, res) => { const { username, email, password } = req.body; const passwordHash = await bcrypt.hash(password, 10); const user = new User({ username, email, passwordHash }); user.save((err, user) => { if (err) { console.error(err); res.status(500).send('Error registering new user.'); } else { const token = generateAccessToken({ username, email }); res.json({ token }); } }); }); app.post('/login', async (req, res) => { const { email, password } = req.body; const user = await User.findOne({ email }); if (!user) { return res.status(404).send('User not found.'); } const validPassword = await bcrypt.compare(password, user.passwordHash); if (!validPassword) { return res.status(401).send('Invalid password.'); } const token = generateAccessToken({ username: user.username, email }); res.json({ token }); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
This code creates an Express app with routes for registration and login. It also uses Mongoose to connect to a local MongoDB database and bcrypt to hash passwords.
4.6 Testing the Login and Registration System
Now that we have created the frontend and backend components of our login and registration system, we need to test it to make sure everything is working correctly. To test the system, follow these steps:
- In the terminal, navigate to the backend directory and start the backend server by running the command node server.js.
- In a new terminal window, navigate to the frontend directory and start the frontend server by running the command ng serve.
- Open your web browser and go to http://localhost:4200/.
- Click on the “Register” button and fill out the registration form with a unique username, email, and password. Click the “Register” button to submit the form.
- If the registration was successful, you should see a success message and a button to go to the login page. Click the “Go to Login” button.
- Fill out the login form with the email and password you used to register and click the “Login” button.
- If the login was successful, you should see a success message and a button to go to the home page. Click the “Go to Home” button.
- You should now be on the home page and logged in as the user you registered. Congratulations, you have successfully created a login and registration system with Angular, Node.js, and MongoDB!
Conclusion
In this article, we have covered how to create a login and registration system with Angular, Node.js, and MongoDB. We started by creating the frontend components of the system using Angular and then moved on to creating the backend components using Node.js and MongoDB. We also covered how to test the system to make sure everything is working correctly.
Creating a login and registration system is an essential part of building many web applications, and Angular, Node.js, and MongoDB provide a powerful set of tools for creating robust and secure systems. By following the steps in this article, you should now have a good understanding of how to create a login and registration system using these technologies.
FAQ’s
Angular is a popular web application framework created by Google for building dynamic and responsive web applications.
Node.js is a server-side runtime environment that allows developers to run JavaScript code outside of the browser.
MongoDB is a NoSQL document-oriented database that is commonly used for building web applications.
Hashing passwords with bcrypt provides an additional layer of security by making it much more difficult for attackers to crack user passwords.
Yes, you can use a different database with this system by modifying the backend code to use a different database driver.