Table of Contents
Building a Basic Full-Stack Application with Angular.js and Express.js for Beginners
This comprehensive guide is designed to help beginners create a full-stack application using Angular.js for the frontend and Express.js for the backend. We’ll cover the steps from setting up your environment to creating a simple user interface and integrating it with a backend server.
Part 1: Setting Up the Angular.js Frontend
Prerequisites
Before starting, ensure Node.js and npm are installed on your computer, as they are necessary for Angular.js development.
Step 1: Installing Angular CLI
Angular CLI is a powerful tool to initialize, develop, scaffold, and maintain Angular applications. Install it globally using npm:
npm install -g @angular/cli
Code language: CSS (css)
Step 2: Creating a New Angular Project
Generate a new Angular project using the Angular CLI:
ng new my-angular-app
Code language: JavaScript (javascript)
Replace my-angular-app
with your desired project name.
File Structure Overview
After creating your project, your file structure should look like this:
my-angular-app/
|-- node_modules/
|-- src/
| |-- app/
| | |-- user-profile/
| | | |-- user-profile.component.html
| | | |-- user-profile.component.ts
| | | |-- user-profile.component.css
| | |-- app.component.html
| | |-- app.component.ts
| | |-- app.component.css
| | |-- app.module.ts
| |-- index.html
| |-- main.ts
|-- package.json
Understanding the Project Structure
- node_modules/: Contains all your project dependencies.
- src/: The source files for your Angular application.
- app/: Contains your Angular components.
- index.html: The main HTML file for your app.
- main.ts: The main entry point for your Angular application.
Step 3: Building Your First Component
Open src/app/app.component.ts
. This file is the main component in your Angular app.
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'my-angular-app';
}
Code language: JavaScript (javascript)
Step 4: Adding User Profile Functionality
Creating the UserProfile Component
Use Angular CLI to generate a new component named UserProfile
:
ng generate component user-profile
This will create a new directory user-profile
with the necessary files.
user-profile.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
username: string;
password: string;
constructor() {
this.username = '';
this.password = '';
}
submitForm() {
console.log(this.username, this.password);
// Further implementation will be added later
}
}
Code language: JavaScript (javascript)
Integrating UserProfile in app.component.html
In src/app/app.component.html
, use the UserProfile
component:
<div>
<h1>Welcome to {{ title }}</h1>
<app-user-profile></app-user-profile>
</div>
Code language: HTML, XML (xml)
Step 5: Running the Application
Start your Angular app:
ng serve
This command compiles the application and starts a web server. Open your browser to http://localhost:4200
.
Check out the Angular.js documentation to learn more about it’s library.
Part 2: Setting Up the Express.js Backend
Step 1: Initialize a New Node.js Project
Create a new directory for your backend (separate from the Angular project). Initialize a Node.js project:
mkdir my-backend
cd my-backend
npm init -y
Step 2: Installing Express and Body-Parser
Install Express and Body-Parser to create your server and parse incoming JSON payloads:
npm install express body-parser
Step 3: Creating the Express Server
In your my-backend
directory, create a file named server.js
. This file will be the server’s main file.
server.js:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const PORT = 3000;
app.use(bodyParser.json());
let users = []; // Mock database
app.post('/register', (req, res) => {
const { username, password } = req.body;
users.push({ username, password }); // Remember to hash passwords in a real app
res.status(200).json({ message: 'User registered successfully' });
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
Code language: PHP (php)
Step 4: Running the Server
Start the Express server with:
node server.js
Code language: CSS (css)
Your server will be listening for requests on http://localhost:3000
.
Part 3: Integrating Frontend with Backend
Step 1: Installing Angular’s HttpClient Module
In your Angular project, you will use the HttpClient module to make HTTP requests. Open src/app/app.module.ts
and import HttpClientModule
.
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { UserProfileComponent } from './user-profile/user-profile.component';
@NgModule({
declarations: [
AppComponent,
UserProfileComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Code language: JavaScript (javascript)
Step 2: Updating UserProfile for API Interaction
Modify src/app/user-profile/user-profile.component.ts
to send user data to your Express server using Angular’s HttpClient
.
user-profile.component.ts (updated):
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent {
username: string;
password: string;
constructor(private http: HttpClient) {
this.username = '';
this.password = '';
}
submitForm() {
const user = {
username: this.username,
password: this.password
};
this.http.post('http://localhost:3000/register', user)
.subscribe(response => console.log(response));
}
}
Code language: JavaScript (javascript)
Running the Full-Stack Application
- Backend: Ensure your Express server is running (
node server.js
). - Frontend: Start your Angular app (
ng serve
). - Interact with the App: Use the form in your Angular app to register users and observe the server’s response.
Integrating an External API
To integrate an external API into your Angular application, you would follow a similar process as you did for the backend integration. Utilize Angular’s HttpClient
to make requests to the API, handle the responses, and update your component’s state.
Conclusion
Congratulations on building a basic full-stack application using Angular.js and Express.js! This tutorial is a stepping stone into the world of full-stack development. As you continue to learn and grow, explore different Angular features, delve deeper into Express.js, and start building more complex applications, soon you will be ready to start your own website click here for a comprehensive guide. Remember, the journey of learning web development is filled with continuous growth and exciting challenges. Happy coding!