Integrating AngularJS with Node.js backend

Loading

AngularJS is a front-end JavaScript framework for building dynamic web applications, while Node.js is a back-end runtime that allows JavaScript to run server-side. Integrating both enables full-stack JavaScript development, making the application efficient and scalable.

In this guide, we’ll walk through the step-by-step integration of AngularJS with a Node.js backend, covering:

  • Setting up the Node.js server
  • Creating REST APIs using Express.js
  • Connecting AngularJS with Node.js
  • Fetching and displaying data

1. Prerequisites

Before getting started, ensure you have:
Node.js and npm installed – Download from https://nodejs.org
Basic knowledge of AngularJS and Express.js
MongoDB (optional, for database integration)


2. Setting Up the Node.js Backend

A. Create a New Node.js Project

  1. Open the terminal and create a new directory: mkdir angularjs-node-app && cd angularjs-node-app
  2. Initialize a Node.js project: npm init -y This creates a package.json file.

B. Install Dependencies

Install Express.js (for handling HTTP requests) and CORS (to allow cross-origin requests):

npm install express cors body-parser

3. Creating the Node.js Server

A. Create server.js File

Inside your project folder, create server.js and add the following code:

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const PORT = 3000;

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

// Sample Data
let users = [
{ id: 1, name: "Alice", email: "alice@example.com" },
{ id: 2, name: "Bob", email: "bob@example.com" }
];

// API Endpoint to Fetch Users
app.get('/api/users', (req, res) => {
res.json(users);
});

// API Endpoint to Add a New User
app.post('/api/users', (req, res) => {
const newUser = req.body;
newUser.id = users.length + 1;
users.push(newUser);
res.status(201).json(newUser);
});

// Start Server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});

B. Run the Server

Start the Node.js server:

node server.js

You should see:

Server running on http://localhost:3000

The API is now live and can be accessed at http://localhost:3000/api/users.


4. Setting Up the AngularJS Frontend

A. Create the AngularJS Project Structure

Inside the angularjs-node-app folder, create a subfolder for the frontend:

mkdir frontend && cd frontend

Then, create an index.html file and an app.js file inside frontend.

B. Add AngularJS to index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS with Node.js</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="myApp" ng-controller="UserController">
<h2>User List</h2>
<ul>
<li ng-repeat="user in users">{{ user.name }} - {{ user.email }}</li>
</ul>

<h3>Add User</h3>
<input type="text" ng-model="newUser.name" placeholder="Name">
<input type="email" ng-model="newUser.email" placeholder="Email">
<button ng-click="addUser()">Add User</button>
</body>
</html>

5. Connecting AngularJS to Node.js API

A. Configure app.js in AngularJS

Create an app.js file inside frontend and write the following code:

var app = angular.module("myApp", []);

app.controller("UserController", function ($scope, $http) {
$scope.users = [];
$scope.newUser = {};

// Fetch Users from API
$scope.getUsers = function () {
$http.get("http://localhost:3000/api/users")
.then(function (response) {
$scope.users = response.data;
});
};

// Add New User
$scope.addUser = function () {
if (!$scope.newUser.name || !$scope.newUser.email) return;

$http.post("http://localhost:3000/api/users", $scope.newUser)
.then(function (response) {
$scope.users.push(response.data);
$scope.newUser = {}; // Reset form
});
};

// Initialize
$scope.getUsers();
});

6. Running the Full-Stack Application

A. Start the Node.js Backend

node server.js

B. Open index.html in the Browser

  1. Open the frontend folder.
  2. Double-click index.html to open it in a browser.
  3. You should see the list of users retrieved from the backend.

C. Test Adding Users

  • Enter a name and email in the input fields.
  • Click Add User.
  • The new user should appear in the list, and the backend should update.

7. Using MongoDB for Database Storage (Optional)

Instead of using in-memory data, integrate MongoDB as a database.

A. Install Mongoose

npm install mongoose

B. Update server.js

Modify server.js to connect with MongoDB:

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost:27017/usersDB", { useNewUrlParser: true, useUnifiedTopology: true });

const UserSchema = new mongoose.Schema({
name: String,
email: String
});

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

// Fetch Users from Database
app.get("/api/users", async (req, res) => {
const users = await User.find();
res.json(users);
});

// Add User to Database
app.post("/api/users", async (req, res) => {
const newUser = new User(req.body);
await newUser.save();
res.status(201).json(newUser);
});

Run MongoDB locally (mongod) before starting the server. Now, users are stored in a database instead of an array.

Leave a Reply

Your email address will not be published. Required fields are marked *