Creating REST API using Nodejs and consuming in Angularjs

In most of the applications we need to talk to some kind of database. While AngularJS is a client side library which is capable only at the client side or at browser, now to connect to our database which usually resides at our server we need NodeJS.
NodeJS is an awesome light weight, non-blocking platform to have at your server which is perfect for data-intensive real-time applications.
We will create a simple inventory manager app which will communicate to database
Database: products-demo
Collection: products
Fields: SKU, Product Name, Price
Our learning path will be like following
- Install NodeJS and MongoDB
- Create and configure web server to communicate to database (NodeJS + Express)
- Craft the client side app (AngularJS)
Install NodeJS, NPM and MongoDB
- NodeJs: https://nodejs.org/en/
- MongoDB: https://www.mongodb.org/
Create ReST API
- To create a NodeJS application we first need to create 2 files named:
1. package.json (Defines the architecture and dependency of the nodejs app)
{ | |
"name": "ReST-API", | |
"version": "1.0.0", | |
"description": "A simple RESTFul API created using nodejs that talks to Mongodb database", | |
"main": "index.js", | |
"author": "codenx", | |
"license": "ISC", | |
"dependencies": { | |
"body-parser": "^1.13.3", | |
"express": "^4.13.3", | |
"mongoose": "^4.1.3", | |
"node-restful": "^0.2.2" | |
}, | |
"main": "server.js" | |
} |
2. server.js (This will create a basic webserver similar to Apache)
// Dependencies | |
var express = require('express'); | |
var mongoose = require('mongoose'); | |
var bodyParser = require('body-parser'); | |
// MongoDB | |
mongoose.connect(process.env.OPENSHIFT_MONGODB_DB_URL || 'mongodb://localhost/products-demo'); | |
// mongoose.connection.on('error', function(){}); | |
// Express | |
var app = express(); | |
app.use(express.static(__dirname + '/public')); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: true })); | |
// Routes | |
app.use('/api', require('./routes/api')); | |
// Start server | |
var port = process.env.OPENSHIFT_NODEJS_PORT || 8080 | |
, ip = process.env.OPENSHIFT_NODEJS_IP || "127.0.0.1"; | |
app.listen(port, ip, function() { | |
console.log('Express server listening on %d', port); | |
}); |
Now we created our server, lets open command line and navigate to the project folder (C:\creating-rest-api-using-nodejs-and-consuming-in-angularjs) Enter the following commands
npm install node server
npm install – Install all required modules defined in package.json file
- body-parser – Required to parse the JSON data from the client
- express – Webserver similar to Apache
- mongoose – Handy module to talk to MongoDB database
- node-restful – This module automatically create REST API from specified model
node server – Run our NodeJS app
At this point we should see the message Server is running on port 3000 Create the following 2 files
- models/product.js – Define the database schema
app.controller('ProductsCtrl', function($scope, Product, ngProgress, toaster) { | |
$scope.product = new Product(); | |
var refresh = function() { | |
$scope.products = Product.query(); | |
$scope.product =""; | |
} | |
refresh(); | |
$scope.add = function(product) { | |
Product.save(product,function(product){ | |
refresh(); | |
}); | |
}; | |
$scope.update = function(product) { | |
product.$update(function(){ | |
refresh(); | |
}); | |
}; | |
$scope.remove = function(product) { | |
product.$delete(function(){ | |
refresh(); | |
}); | |
}; | |
$scope.edit = function(id) { | |
$scope.product = Product.get({ id: id }); | |
}; | |
$scope.deselect = function() { | |
$scope.product = ""; | |
} | |
}) |
routes/api.js – Defines the API routes (data providers)
- e.g. http://localhost:3000/api/products (get,post,put,delete)
- e.g. http://localhost:3000/api/categories (get,post,put,delete)
// Dependencies | |
var express = require('express'); | |
var router = express.Router(); | |
//Product | |
var Product = require('../models/product'); | |
Product.methods(['get', 'put', 'post', 'delete']); | |
Product.register(router, '/products'); | |
// Return router | |
module.exports = router; |
Now that our API is ready. You can test it using Chrome Postman extension
The next step is to create our client using AngularJS To call our ReST API we need the help of angular-resource which will make our task easy and fun. In this application I’ve added some animations too. For this application we will create a factory named Product to interact with our ReST API which in turn interacts with our database. We will call this factory from products.js file with different methods like get, post, put, delete. The file public/index.html is the starting point of our application. From here everything starts. This page renders the view.
<!DOCTYPE> | |
<html ng-app="myApp"> | |
<head> | |
<title>Simple demonstration of AngularJS with ReSTful API - AngularCode</title> | |
<link rel="stylesheet" href="css/bootstrap.min.css"> | |
<link rel="stylesheet" href="css/ngProgress.css"> | |
<link rel="stylesheet" href="css/toaster.css"> | |
<style> | |
[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak { | |
display: none !important; | |
} | |
</style> | |
</head> | |
<body ng-cloak> | |
<div class="container" ng-controller="ProductsCtrl"> | |
<form name="Codenx" novalidate> | |
<table class="table"> | |
<thead> | |
<tr> | |
<th>Name</th> | |
<th>SKU</th> | |
<th>Price</th> | |
<th>Action</th> | |
<th> </th> | |
</tr> | |
</thead> | |
<tbody> | |
<tr> | |
<td><input class="form-control" ng-model="product.name" required="" placeholder="Product Name"></td> | |
<td><input class="form-control" ng-model="product.sku" placeholder="Stock Control Unit"></td> | |
<td><input class="form-control" ng-model="product.price" placeholder="Should be a number"></td> | |
<td><button class="btn btn-primary" ng-click="add(product)" ng-if="!product._id" type="submit" ng-disabled="!Codenx.$valid">Add Product</button> | |
<div class="btn-group"> | |
<button class="btn btn-info" ng-click="update(product)" ng-if="product._id" type="submit">Update</button> | |
<button class="btn" ng-click="deselect()" ng-if="product._id">Clear</button> | |
</div> | |
</td> | |
</tr> | |
<tr ng-repeat="product in products"> | |
<td>{{product.name}}</td> | |
<td>{{product.sku}}</td> | |
<td>{{product.price}}</td> | |
<td> | |
<div class="btn-group"> | |
<button class="btn btn-danger" ng-click="remove(product)">Remove</button> | |
<button class="btn btn-warning" ng-click="edit(product._id)">Edit</button> | |
</div> | |
</td> | |
</tr> | |
</tbody> | |
</table> | |
</form> | |
</div> | |
<div data-loading></div> | |
<toaster-container toaster-options="{'time-out': 3000, 'close-button':true, 'animation-class': 'toast-top-center'}"></toaster-container> | |
<script src="js/angular.min.js"></script> | |
<script src="js/angular-resource.min.js"></script> | |
<script src="js/angular-animate.min.js"></script> | |
<script src="js/ngProgress.min.js"></script> | |
<script src="js/toaster.js"></script> | |
<script src="app/app.js"></script> | |
<script src="app/products.js"></script> | |
</body> | |
</html> |
We have 2 controller where we define the business logic and the angular app resides here
app/app.js
var app = angular.module('myApp', ['ngResource', 'ngProgress', 'ngAnimate', 'toaster']); | |
app.config(function ($httpProvider) { | |
$httpProvider.interceptors.push('myHttpInterceptor'); | |
}); | |
// Handle http server errors | |
app.factory('myHttpInterceptor', function ($q,toaster) { | |
return { | |
responseError: function (response) { | |
console.log(response); | |
if(response.data){ | |
if(response.data.message) | |
toaster.error("Error: ", response.data.message); | |
else | |
toaster.error("Error: ", response.data); | |
} | |
return $q.reject(response); | |
} | |
}; | |
}); | |
// Showing loading indicator on top while data is requested from database | |
app.directive('loading', ['$http', 'ngProgress', function ($http, ngProgress) | |
{ | |
return { | |
restrict: 'A', | |
link: function (scope, elm, attrs) | |
{ | |
scope.isLoading = function () { | |
return $http.pendingRequests.length > 0; | |
}; | |
scope.$watch(scope.isLoading, function (v) | |
{ | |
if(v){ | |
ngProgress.start(); | |
}else{ | |
ngProgress.complete(); | |
} | |
}); | |
} | |
}; | |
}]); | |
// Create a resource factory to access products table from database | |
app.factory('Product', function($resource) { | |
return $resource('/api/products/:id', { id: '@_id' }, { | |
update: { // We need to define this method manually as it is not provided with ng-resource | |
method: 'PUT' | |
} | |
}); | |
}); |
app/products.js
This is the ProductsCtrl where we handle all user interactivity
// Dependencies | |
var restful = require('node-restful'); | |
var mongoose = restful.mongoose; | |
// Schema | |
var productSchema = new mongoose.Schema({ | |
name: String, | |
sku: String, | |
price: Number | |
}); | |
// Return model | |
module.exports = restful.model('Products', productSchema); |

Most Popular Posts
- ShopNx - The assistant manager for influencers
- Frontendfun marketplace for software projects
- Complete steps to configure elasticsearch on Ubuntu
- Configure Vultr for Nodejs Deployment
- Appointment Booking Microservice using Javascript Fullstack
- 100+ most effective ways to promote a new blog for free
- Steps to Configure Digital Ocean Droplet for Nodejs Application Deployment
- Appointment Booking using Angularjs, Nodejs, Mongodb
- Send email with PDF attachment using PHP
- Simple task manager application using Angularjs PHP Mysql
- Steps to Configure Amazon EC2 for Nodejs app deployment
- Inventory Manager Using Angularjs Mysql Php
- User authentication using Angularjs, PHP, Mysql
- Demo of a simple CRUD Restful php service used with Angularjs and Mysql
- Simple file upload example using Angularjs
- Generate PDF using PHP from Mysql database
- Creating REST API using Nodejs and consuming in Angularjs
- Simple project demonstrates how to send email using Nodejs
- Voting system similar to stackoverflow using Angularjs PHP and Mysql
- Angularjs datagrid paging, sorting, filter using PHP and Mysql
- Useful database helper class to generate CRUD statements using PHP and Mysql
- Online Shopping Mega Menu using Angularjs, PHP, Mysql
- How to create a facebook style autocomplete using Angularjs
- Steps configuring PHP Cron Jobs - Godaddy
- How to change Mysql password
- A simple Angularjs web app that converts text to url format
- Creating SWAP file on Linux