Connecting Angular Frontend to a Node.js Backend
🔗 Connecting Angular Frontend to a Node.js Backend
Integrating an Angular app with a Node.js backend allows you to build full-stack applications where the frontend communicates with the backend to retrieve, add, update, or delete data.
✅ Prerequisites
Node.js and Angular CLI installed
A working Angular app (ng new my-app)
A RESTful API built with Node.js and Express
🛠 1. Start with the Backend (Node.js + Express)
Here’s a simple Express API example:
js
Copy
Edit
// backend/index.js
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors()); // Allow cross-origin requests
app.use(express.json());
let data = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' }
];
app.get('/api/items', (req, res) => {
res.json(data);
});
app.post('/api/items', (req, res) => {
const newItem = { id: data.length + 1, name: req.body.name };
data.push(newItem);
res.status(201).json(newItem);
});
app.listen(3000, () => {
console.log('Backend running on http://localhost:3000');
});
Run it with:
bash
Copy
Edit
node index.js
🌐 2. Make HTTP Requests from Angular
In your Angular app:
a. Generate a Service
bash
Copy
Edit
ng generate service item
b. Use HttpClient in the Service
ts
Copy
Edit
// src/app/item.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ItemService {
private apiUrl = 'http://localhost:3000/api/items';
constructor(private http: HttpClient) {}
getItems(): Observable<any> {
return this.http.get(this.apiUrl);
}
addItem(name: string): Observable<any> {
return this.http.post(this.apiUrl, { name });
}
}
c. Inject Service into Component
ts
Copy
Edit
// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { ItemService } from './item.service';
@Component({
selector: 'app-root',
template: `
<h2>Items</h2>
<ul>
<li *ngFor="let item of items">{{ item.name }}</li>
</ul>
<input [(ngModel)]="newItem" placeholder="New item">
<button (click)="addItem()">Add</button>
`
})
export class AppComponent implements OnInit {
items: any[] = [];
newItem: string = '';
constructor(private itemService: ItemService) {}
ngOnInit() {
this.loadItems();
}
loadItems() {
this.itemService.getItems().subscribe(data => this.items = data);
}
addItem() {
if (this.newItem.trim()) {
this.itemService.addItem(this.newItem).subscribe(() => {
this.newItem = '';
this.loadItems();
});
}
}
}
🔄 3. Enable CORS on the Backend
Ensure your Express backend uses the cors package so Angular can connect without CORS issues:
bash
Copy
Edit
npm install cors
Add app.use(cors()); in your Express app (as shown earlier).
🎉 That’s It!
Now your Angular frontend can successfully communicate with your Node.js backend using HTTP requests.
Would you like to add authentication or connect to a database next?
Learn Mean Stack Course
Read More
Top 5 Reasons to Learn the MEAN Stack in 2025
What is the best free online Node JS course or tutorial?
Visit Our Quality Thought Training in Hyderabad
Comments
Post a Comment