Posts on this Category



Node.js: How to make POST Requests with JSON data

In this post I’m going to show you how to work with POST requests, I’ll give you an example as simple as possible. First I’ll create the Nodejs app to receive the requests, then I’ll show you how to make the requests from the frontend.

We’re going to be using Expressjs, it’s a very popular npm package, you probably already heard of it, but if you don’t, just click here to see the instructions on how to create your project. You can also add express to an existing project via npm, but in this case you’ll have to add the body-parser as well.

Express creates a basic project structure for us, but most of it will not be used in this example, so I’m going to open my app.js and get rid of almost everything, this is the minimum we need to create requests routes:

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
 
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
 
<pre lang="javascript">
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
 
module.exports = app;

Now let’s create our first route, I’m putting it at the end, right above the module.exports line:

app.post('/test', (request, response) => {
   console.log(request.body);
   response.json(request.body);
});

Here I’m using the express post function to create the route, it receives the path, which in this case is /test and a callback function to handle the request. Note that this function has two parameters, request and response. The first contains the JSON data passed by the client, it can be accessed through the attribute body. The second is where we put the result, so the client can receive it when the request completes.

In this example, after receiving a request the server will print the JSON dataset sent by the client and then send back the exact same data.

Ok, we’re done with the server-side now, let’s see how to make requests with the Fetch API on the frontend.

var data = [{"username": "dmccreadie0"}, 
   {"username": "bwillerson1"}, 
   {"username": "fteese2"}, 
   {"username": "dsummerell3"}];
 
fetch('http://localhost:3000/test', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {'Content-Type': 'application/json'}
}).then(response => { 
  return response.json(); 
}).then(data => { 
  alert(JSON.stringify(data));
}).catch(err => {
    alert(err);
});

The variable data is a simple JSON dataset I’ve created to use as an example. When making a request with fetch() we have to pass the URL, which in this case is http://localhost:3000/test, and an object containing the request options (method, body and header). To include the JSON data in the request we have to convert it to string and assign it to the body attribute, this way the server will be able to retrieve this data as we saw before.

Lastly, let’s see how to get the data sent by the server. The function then() allows us to add a callback that handles the response. To retrieve our data we just have to use the function json(). In this example I’m just extracting the JSON from the response and showing it to the user with an alert dialog.

That’s pretty much it guys, of course there’s much more we can do here, it’s a big topic, but as I said this is just a basic example. If you have any doubts don’t hesitate to ask in the comments.

Express.js: How to Change the Default Port

By default Express uses port 3000, but sometimes this port is already been used by another application, so you can either close the other application or change the port. In this short tutorial I’m going to show you how easy it is to change the port.

First let’s open the bin/www file and locate this code:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

Here is where we can configure which ports to use, all you have to do is to replace the number 3000 by another port number. After that your application will not be using port 3000 anymore.

Alternatively you can also configure the port on your app.js:

var app = express();
app.listen(4000);

As you can see I’ve just added the app.listen(4000) line, this will make the application also listen on port 4000, but the difference is that this method won’t make your app stop using port 3000.

It’s up to you to decide which method works better for you, If you have any doubts please let me know in the comments.

Nodejs Totorial: Creating and Using Events

Nodejs makes it very easy for us to use events, and we’re not limited to a collection of predefined events, it has a built-in module that allows us create and emit our own events.

Let me show you how easy it is to use this module, first we have require the events module and create the event emitter:

var ev = require('events');
var emitter = new ev.EventEmitter();

Ok, now we’re ready to start creating the events. As an example I’m going to use an event that I named new user, let’s create its event listener:

emitter.on('new user', function(){
   console.log('A new user has connected.');
});

I’ve used the function on from the EventEmitter to add this event listener, it receives the event name and a callback function that executes once the event is triggered.

Now the application is already listening the new user event, this is how we can emit it:

emitter.emit('new user');

Simple right? All we have to do is to call the emit function passing the event name.

But what if we have to pass parameters when emitting the event? Optionally, you can also pass some arguments to the emit function if you need, then you just have to declare them on the callback function as well. Here’s an example:

emitter.on('new user', function(user){
   console.log('The user '+user+' has connected.');
});
 
emitter.emit('new user','user1');

That’s it guys! Thanks for reading, if you have any doubts please let me know in the comments.

Tutorial: Creating a Realtime Notification System in Angular and Nodejs

Notification System Demo
Notification System Demo

In this post I’m going to show you how to create a simple realtime notification system using Angular, Nodejs and Socket.io. It will offer a page where we will be able to create notifications and broadcast it to all the online users. I’ll be making it as basic as possible, once we’re done we can add more functionalities. This application will have the frontend and the backend separeted in 2 different projects, we’re going to use Angular in the frontend and Nodejs in the backend. Let’s start with the backend.

Creating the Nodejs Project

I’m using Expressjs to create the Node.js project, if you don’t have express you can install it globally via:

npm install express-generator -g

After installing it you can create your project with the command:

express notifications-backend

In this case ‘notifications-backend’ is the project name, but you can give a name of your choice. Now you already have a basic expressjs project, if you run your project with npm start and type the url localhost:3000 on your browser you’ll see a welcome page. By default expressjs create some views for us, we’re not going to be using them though, so feel free to delete them if you want. All of our views will be on the frontend project, this one will only be responsible for managing the notifications.

Creating the Socket.io Server

The next step is to add socket.io to the project:

npm install --save socket.io

Socket.io is what makes our application realtime, it’s event-based, which means when an event happens, it triggers something. All the events are specified by us, we can create as many as we want, but our application only needs two, I’m going to name them create notification and new notification.

create notification: This event will be emitted by the client-side when a user creates a notification. The server will always be listening to this event, this is how it will know a notification was created.

new notification: This one will be emitted by the server-side when it receives a newly created notification. As opposed to the previous event, this one will be listened by every client, once they receive this event they will just show the notification to the user.

This is our server-side socket.io code, I’m putting it on the app.js just bellow the var app = express(); line.

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
io.set("origins", "*:*");
server.listen(8000);                                 
 
io.on('connection', function(socket){                
  socket.on('create notification', function(data){   
    socket.broadcast.emit('new notification',data);  
  });
});

Before we analyze the code we should know the socket.io on function, that’s the function we use to add event listeners to the application, it receives the event name and a callback function that will be executed when the event fires. You should also be familiar with the function emit and broadcast.emit, the first one emits an event to all the clients as the second emits to everyone except the client who fired it.

Now If you take a look at the code you’ll see that the first 5 lines are just to create the socket server, next I’m adding an event listener to the connection event, so every time a new client connects this event will call a callback function that adds a listener to the create notification event, which when triggered will emit the new notification event broadcasting the message to all the users.

We are pretty much done with the backend now, time to start working on the frontend!

Creating the Angular Project

If it’s the first time you’re using Angular you have to install @angular/cli before you proceed.

npm install -g @angular/cli

Now you can create your project.

ng new notifications-frontend

Again, notifications-frontend is my project name, you can change it if you want. The command above will download and install all the dependencies on your project, so it may take a while. After creating the project we have to install socket.io on this one as well, but the installation is a little bit different from the backend, click here to see the instructions.

Now we have the basic project structure, we’ll be creating two components, app.adminComponent.ts and app.userComponent.ts, the first one is the page where the admin will be able to send notifications to all the other users, and the second is a component that represents any page that a user have access to, its only functionality will be to receive the notification.

app.adminComponent.ts

import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
 
@Component({
  selector: 'admin-component',
  templateUrl: './app.adminComponent.html'
})
export class AdminComponent {
 
   constructor(private socket: Socket) {}
 
   sendNotification(){
      this.socket.emit('create notification','Notification Test');
   }
}

Here we have the admin-component, note that I’m declaring the socket on the constructor, besides that I’ve created only one function, the sendNotification, which will be responsible for emitting create notification event. Remember when we created its listener on the server side? This is how it’s going to be triggered.

You have probably noticed that this component uses a template. Here is the code:

<div style="text-align:center">
   <button (click)="sendNotification()">Send Notification</button>
</div>

Nothing special here, it contains only a button that calls the sendNotification function.

app.userComponent.ts

import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
 
@Component({
  selector: 'user-component',
  template: ''
})
export class UserComponent {
 
   constructor(private socket: Socket) { 
      socket.on('new notification', function(data){
         alert(data)
      });
   }
}

This one is even simpler than the previous, the only thing I’m doing here is adding an event listener to the new notification event, which is the event for receiving a notification. Once it fires it will show the notification message to the user with an alert dialog.

Routing and Navigation

We’re almost done, the last thing we have to do is to add the routes, that’s what will allow us to navigate between the two components. We will define two routes, user and admin, so our components will be accessed by the urls http://localhost:4200/user and http://localhost:4200/admin respectively.

Here is how we can define the routes on the app.module.ts file:

//other imports
import { RouterModule, Routes } from '@angular/router';
 
const appRoutes: Routes = [
  { path: 'user', component: UserComponent },
  { path: 'admin', component: AdminComponent },
];
 
@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes),
    //other imports
  ],
  ...
})
export class AppModule { }

As you can see I’ve created the array appRoutes, here is where we declare all of our routes mapping the paths to the components, then we pass it to the RouterModule.forRoot function on the module imports.

Lastly let’s open the app.component.ts, that’s the default component that was already there when we created the project. We’re only using this component to put the router-outlet, which will just display the component that matches the path on the Url.

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  template: `
    <router-outlet></router-outlet>
  `
})
export class AppComponent { }

That’s it guys! Your application should be working now, hope you liked the tutorial. If you have any doubts please let me know in the comments.

Node Express Error: Cannot find module ‘serve-favicon’

This error means you don’t have the module ‘serve-favicon’ installed on your project, here is the full error:

Error: Cannot find module 'serve-favicon'
    at Function.Module._resolveFilename (module.js:542:15)
    at Function.Module._load (module.js:472:25)
    at Module.require (module.js:585:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (C:\project\a2-notifications\app.js:3:15)
    at Module._compile (module.js:641:30)
    at Object.Module._extensions..js (module.js:652:10)
    at Module.load (module.js:560:32)
    at tryModuleLoad (module.js:503:12)
    at Function.Module._load (module.js:495:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! notifications@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the myapp@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional log
ging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to in
stall?

Buf if you are getting this error the ‘serve-favicon’ is probably not the only module missing. My guess is that you forgot to install the dependencies before running your project with npm start. Try executing npm install first, this command will download all the dependencies for you, after that your problem should be solved.

Angular2 Tutorial: Developing a Realtime Chat App

Angular 2 Chat Application
Angular 2 Chat Application

Hi guys, today we’re going to make an awesome chat application with Angular2, NodeJS and Socket.io, this tutorial will involve quite a lot of things, and there are also lots of small details, so it will be a little bit longer than usual. To easily understand and make the most of it you should already have some knowledge about all the frameworks involved, if something is unclear for you please let me know in the comments, I’ll try to explain it better. With that in mind let’s stop wasting time and get started!

Setting up the Environment

I’m going to use Express to create my project, if you’re new to express and don’t know how to do it click here to see the instructions. After creating the project there will be a file called package.json on the project folder, that’s where all the dependencies are listed, open this file and copy/paste the following code:

{
  "name": "angular2-chat",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "postinstall": "npm run typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
    "typings" : "typings"
  },
   "license": "ISC",
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "angular2": "2.0.0-beta.16",
    "systemjs": "0.19.26",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.35.0",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.2",
    "zone.js": "0.6.12",
    "socket.io":"1.4.5"
  },
  "devDependencies": {
    "concurrently": "^2.0.0",
    "lite-server": "^2.2.0",
    "typescript": "^1.8.10",
    "typings":"^0.8.1"
  }
}

Besides the NodeJS and Express dependencies (which were already there), I’ve also added Socket.io and everything related to Angular2. If you run the command npm install on your terminal it’ll download and put all the dependencies on a folder called /node_modules. Lots of scripts from this folder will be used on the front-end, so we have to reference them on the index.html file, which we’re going to create right now.

Open the /views folder and create the index.html with the following code:

<html>
  <head>
    <base href="/">
    <title>Chat</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <script 
      src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script> 
    <script src="scripts/es6-shim/es6-shim.min.js"></script>
    <script src="scripts/systemjs/dist/system-polyfills.js"></script>
    <script src="scripts/angular2/bundles/angular2-polyfills.js"></script>
    <script src="scripts/systemjs/dist/system.src.js"></script>
    <script src="scripts/rxjs/bundles/Rx.js"></script>
    <script src="scripts/angular2/bundles/angular2.dev.js"></script>
    <script src="scripts/angular2/bundles/router.dev.js"></script>
    <script src="javascripts/jquery.js"></script>
    <link rel="stylesheet" 
      href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/css/materialize.min.css">
    <script 
      src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.5/js/materialize.min.js"></script>
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('javascripts/app/main.js')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <chat-app>Loading...</chat-app>
  </body>
</html>

This file is very similar to the one from Angular2 Quickstart, but as you can see I’ve added three more scripts: Socket.io and the Materialize css and js files (materialize is a CSS framework we’re going to use for styling). If you pay attention to this code you should notice that I’m not referencing the scripts from /node_modules, instead they’re coming from a folder called /scripts. But where does this folder come from? I’m going to explain in a moment.

One more thing, in order to make Angular2 work you’ll need three more configuration files : tsconfig.json, typings.json and main.ts. All of them can be found on the Angular2 Quickstart.

Now let’s open the app.js file that Exapress created for us, you’ll see that it already has some code, in order to make things easier I’m going to get rid of some lines of code we don’t need, after the modifications the file should look like this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
 
app.use('/scripts', express.static(__dirname + '/node_modules/'));
app.use('/templates', express.static(__dirname + '/views/templates/'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/', routes);
 
/* Handle 404. */
app.use(function(req, res, next) {
  res.sendFile(path.join(__dirname, 'views', 'index.html'));
});
 
module.exports = app;

Just after the var app = express(); line I’ve configured the paths /scripts (which we saw in the index.html) and /templates to serve some static files from /node_modules and /views/templates respectively. I had to do this because by default Angular 2 won’t have access to these folders. But now, if I request a file from /scripts this configuration will make NodeJS understand that it’s located on /node_modules.

At the end of the code (just above module.exports) I’ve changed how 404 errors are handled, instead of forwarding an error (as it was before) I’m redirecting to index.html. This will avoid some problems when we start using Angular2 routes.

Another thing we have to do is to make NodeJS and Angular2 work together, open the file /routes/index.js and replace the existing code with the following:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

By default it was rendering a .jade file (express uses jade as the default view engine), and as I’m not interested in jade for this project I just changed this file a little bit in order to make it redirect to my index.html where Angular2 can control the views. For more details about this modification click here.

At this point we’ve already configured everything we need in our project to start developing our chat app, new let’s start talking about how the application is going to work.

Defining the Structure

Our chat app will be composed of three Angular2 components, the first one will be a form where the user will be allowed to enter his name and join the chat, the second will be the chat itself, and the last will be where we’re going to configure to routes for controlling which of the other two components should be displayed.

On the back-end we’ll have Socket.io being responsible for receiving the messages and delivering them to all the other users, we won’t store the messages there, each client will have its own messages list where every received message will be added.

Creating the Socket.io Server

Before we proceed to the front-end we first have to create the Socket.io server and prepare it to receive messages from the clients, to do that you have to create a new file on your project root folder called socket.js with the following code:

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
 
var chat = {
	start: function(){
		server.listen(8000);
		io.set("origins", "*:*");
 
		io.on('connection', function (socket) {         // line 12
			socket.on('newMessage', function (data) {
				socket.emit('chatUpdate',data);
				socket.broadcast.emit('chatUpdate',data);
			});
			socket.on('newUser', function (data) {
				socket.emit('chatUpdate',
					{'userName':'','text':data+' has entered the room'});
				socket.broadcast.emit('chatUpdate',
					{'userName':'','text':data+' has entered the room'});
			});
		});	
	}
}
 
module.exports = chat;

Now probably is the best time for me to explain how Socket.io works, according to the official site Socket.IO is a framework that enables real-time bidirectional event-based communication, in other words you can create your own events that will allow the server to communicate with the clients and vice-versa. You can add listeners to these events and also emit events from both sides (client and server), once an event is emitted it will trigger its listener on the other side to execute an specific task. To emit events you can use the function emit() passing the event name and your data, and to add a listener you have to use the function on() with the event name as the first parameter and the callback function as the second.

Easy, right? Now that you understand how Socket.io works let’s analyze our code. The first thing I did here was to create a socket.io server that listens on port 8000, but let’s focus on the events, on the server side there is one event that we always have to use in order to start the communication with the clients, this event is called connection, it will be automatically emitted by the each client when it connects to the server (obviously), clearly we have to add a listener to proceed with the communication, as you can see in the code I’m doing it on line 12. Now take a look at the callback function associated with this listener, you’ll see that it’s registering listeners for two more events: newMessage and newUser. The first one is emitted when a user sends a message, and the second one when a new user joins the chat, the action performed by both is very similar, they will just emit another event called chatUpdate to notify all the connected clients about the new message or user. Note that when I emit this event I’m using both socket.emit() and socket.broadcast.emit(), the first one will notify the client who triggered the event, and the second will do the same to all the other clients.

Let’s add the following two lines bellow the var app = express(); on our app.js:

var socketServer = require('./socket');
socketServer.start();

Perfect! This will make the socket.io server initialize right after the application starts. We’re done with the back-end now, let’s start creating the angular2 components.

Creating the User Registration Component

We can finally start writing some Angular2 code, open the /public/javascripts folder and create a new one called /app, that’s where we’re going to put our angular2 components. Open this new folder and add a new file called userRegistration.component.js, then copy/paste the following code:

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
 
@Component({
    selector: 'user-registration',
    templateUrl: 'templates/registration.html'
})
export class UserRegistrationComponent {
    userName = '';
    socket = null;
 
    constructor(
        private _router: Router){}
 
    ngOnInit() {
        this.socket = io('http://localhost:8000');
    }
 
    login() {
        if (this.userName !== null){
            sessionStorage.setItem("userName", this.userName);
            this._router.navigate(['Chat']);
            this.socket.emit('newUser', this.userName);
        }
    }
 
    keypressHandler(event) {
        if (event.keyCode  === 13){
            this.login();
        }
    } 
}

This will be the component where the user is going to enter his name and join the chat, I’ve used the hook ngOnInit to connect to the Websocket server, this will automatically emit the connection event I just talked about. I also have the login() method, which is responsible for putting the provided userName on the sessionStorage and emit the newUser event. Although I’m using the sessionStorage to store the user, I don’t recommend you to do it, it’s not very safe, any user with some javascript knowledge will be able to modify what’s in the sessionStorge.

Note that I’ve created a new file to put the template, it’s called registration.html and it’s located on the folder /views/templates, here’s the code:

<style type="text/css">
	.registrationContainer{margin-top:20%;padding:15px;box-shadow: 3px 2px 7px -1px}
	.registrationContainer button{float: right;}
</style>
<div class="container">
	<div class="col s11 registrationContainer">
 
        <div class="row">
            <div class="input-field col s12">
                <input [(ngModel)]="userName" id="userName" 
                	type="text" (keypress)="keypressHandler($event)">
                <label for="userName">Please enter your name</label>
            </div>
        </div>
	    <button (click)="login()" type="submit" 
	    	class="btn waves-effect waves-light col s3"  
	    	name="action" >Login</button>
	    <div style="clear:both;"></div>
	</div>
</div>

Nothing special here, just an input where the user can type his name and a button to call the login() function. The CSS classes you can see here are from materialize.

Creating the Chat Component

Now comes the most important part, the chat.component.ts:

import {Component} from 'angular2/core';
import {Router} from 'angular2/router';
 
@Component({
    selector: 'chat',
    templateUrl: 'templates/chat.html'
})
export class ChatComponent {
    message = '';
    conversation = [];
    socket = null;
 
    constructor(
        private _router: Router){}
 
    ngOnInit() {
        if (sessionStorage.getItem("userName") === null){
            this._router.navigate(['Registration']);
        }
        this.socket = io('http://localhost:8000');
        this.socket.on('chatUpdate', function(data) {
            this.conversation.push(data);
        }.bind(this));
    }
 
    send() {
        this.socket.emit('newMessage', {
            'userName': sessionStorage.getItem("userName"),
            'text': this.message
        });
        this.message = '';
    }
 
    keypressHandler(event) {
        if (event.keyCode === 13){
            this.send();
        }
    } 
 
    isNewUserAlert(data){
        return data.userName === '';
    }
}

Again I’m using the ngOnInit hook to connect to server, but this time there are a couple more things I’m doing here, I’m checking the sessionStorage to see if it contains the userName, if it doesn’t the user will be redirected to the registration component, and I’m also adding a listener to the chatUpdate event, so when a new message arrives it’ll be added to the conversation array.

The send() method is responsible for triggering the newMessage event, it just get the message typed by the user and send it to the server, it’ll be executed when the user click on the send button or press enter.

Here’s the template:

<style type="text/css">
	.userLabel{font-weight:bold;color:#26A69A;margin-right:10px}
	.chatContainer{height:85%;padding:15px;overflow-y:auto }
</style>
<div class="col s12">
	<div class="col s12 chatContainer">
        <ul *ngFor="#msg of conversation" style="margin:0">
            <li >
            	<div *ngIf="!isNewUserAlert(msg)">
	                <span  class="userLabel" >{{msg.userName}}:</span>
	                <span>{{msg.text}}</span>
                </div>
            	<div *ngIf="isNewUserAlert(msg)">
            		<span style="font-weight:bold">{{msg.text}}</span>
	            </div>
            </li>
        </ul>
	</div>
	<div class="row">
		<div class="col s9">
          <input id="country" type="text"  
          	[(ngModel)]="message" 
          	(keypress)="keypressHandler($event)">
        </div>
		<button (click)="send()"  type="submit" 
			class="btn waves-effect waves-light s2"  name="action" >Send</button>
	</div>
</div>

Lastly we have the component app.component.ts to control the routing, with RouteConfig I’m defining the two possible routes of our app, this allows the other components to redirect from one to another. Note that in the template I have only the router-outlet which will basically render the component related to the current route.

import {Component} from 'angular2/core';
import {UserRegistrationComponent} from 'javascripts/app/userRegistration.component.js';
import {ChatComponent} from 'javascripts/app/chat.component.js';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';
 
@Component({
    selector: 'chat-app',
    directives: [ROUTER_DIRECTIVES],
    template: `
            <router-outlet></router-outlet>
        `
})
@RouteConfig([ 
    { path: '/chat', name: 'Chat', component: ChatComponent, useAsDefault:true },
    { path: '/registration', name: 'Registration', component: UserRegistrationComponent }
])
export class AppComponent {}

To make the routes work we have to make a little modification in our main.ts, just add the ROUTER_PROVIDERS as follows:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from 'javascripts/app/app.component.js'
import {ROUTER_PROVIDERS} from 'angular2/router'
 
bootstrap(AppComponent, [ROUTER_PROVIDERS]);

That’s it guys, we’ve completed our chat app, to run it just execute npm start and access it on your browser by typing localhost:3000. If you have any doubts please let me know in the comments, till next time!

Creating a NodeJS project with Express

Express is one of the most popular npm packages out there, it’s basically a NodeJS web application framework that provides lots of functionalities and helps you to manage everything and organize your app into MVC on the back-end, and it’s very easy to get started with.

To use Express you first need to have NodeJS installed (obviously), if you don’t have it yet click here and download the appropriate version for your OS. With nodejs installed you can now create your your project and start using express, in this tutorial I’m just going to cover how to create the project, but in the future I’ll probably write more about it.

Express has a tool called express-generator that is used to create the project’s basic structure, to install it just use the command:

npm install express-generator -g

Now that we’ve installed it globally we’re ready to create the project, open your terminal and navigate to the folder where you want to put your project, then simply run the command:

express myFirstExpressApp

Done! Now you have a folder called myFirstExpressApp (or any other name you’ve chosen), if you go inside it you’ll see the project files and the following folder structure:

Express Basic Project Structure
Express Basic Project Structure

Creating a Live Auction App with Angular 2, Node.js and Socket.IO

Angular 2 Auction App
Angular 2 Auction App

In this tutorial we’re going to build a very cool Live Auction Application, my goal is to demonstrate how Angular 2, Node.js and Socket.io work together, and as everyone knows Angular 2 will soon come out so I thought it would be great to write a tutorial involving it. Of course our app won’t have all the features a real auction app has, this is just an example to demonstrate how to integrate the frameworks I mentioned.

Setting up the Environment

The first step is to configure the environment, let’s get started by creating our Node.js project, I’m going to use express to do it, if you don’t have it open your terminal and run the command npm install express-generator -g to install, then you can create the project with the command expess {project name} (replace {project name} with your actual project name).

Now you have the basic project structure created for you, but we need to make some changes in order add Angular 2 and Socket.io to the project, first open your package.json and paste the following code:

{
  "name": "auction",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "postinstall": "npm run typings install",
    "tsc": "tsc",
    "tsc:w": "tsc -w",
    "start": "concurrent \"node ./bin/www\" \"npm run tsc:w\"",
    "typings" : "typings"
  },
   "license": "ISC",
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "serve-favicon": "~2.3.0",
    "angular2": "2.0.0-beta.6",
    "systemjs": "0.19.20",
    "es6-promise": "^3.0.2",
    "es6-shim": "^0.33.3",
    "reflect-metadata": "0.1.2",
    "rxjs": "5.0.0-beta.0",
    "zone.js": "0.5.14",
    "socket.io":"1.4.5"
  },
  "devDependencies": {
    "concurrently": "^1.0.0",
    "lite-server": "^2.0.1",
    "typescript": "^1.7.5",
    "typings":"^0.6.8"
  }
}

Now create another file called tsconfig.json in the project root folder and put the following into the file:

{
  "compilerOptions": {
    "target": "es5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

Also in the root folder create the typings.json and copy/paste the following code into it:

{
  "ambientDependencies": {
    "es6-shim": "github:DefinitelyTyped/DefinitelyTyped/es6-shim
/es6-shim.d.ts#6697d6f7dadbf5773cb40ecda35a76027e0783b2"
  }
}

Ok, we have now created all the configuration files, but before we continue you have to install the dependencies by running the command npm install on the terminal.

If you open your app.js you’ll see that express has already put some code in there, in order to make it as simple as possible let’s delete the code we don’t need, after the modification your app.js should look like this:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
 
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
 
app.use('/', routes);
 
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});
 
module.exports = app;

By default express sets jade as the view engine, we’ve already deleted the lines responsible for that in the app.js, but if you check the folder /views you’ll see some .jade files, you can delete them if you want, later we’re going to place our Angular 2 HTML pages in this folder, but for now you can just create and leave an empty index.html in there.

After getting rid of the .jade files we have to tell Node.js that we want to use our index.html instead, we can do that by changing a little bit the code in the routes/index.js file, just open the file and replace its content with the following code:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

To make sure it’s working run your project with the command npm start then enter the url http://localhost:3000/ in your browser, it should display an empty page, write something in the index.html you created and refresh the page, if it appears on the browser you’ve done everything right! Now we’re ready to actually start writing some code.

Introducing Socket.IO

As we know, an auction app must be real-time, which means that when a user places a bid all the other connected users must instantly see it, that’s where Socket.IO comes in, it allows Node.js to receive and broadcast events to all connected clients, so when a user places a bid Socket.IO will emit an event to the server which will update the product price and broadcast it to the other users.

Now let’s see how that looks like in code, copy the following code and paste bellow the var app = express(); in your app.js:

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
io.set("origins", "*:*");
 
var currentPrice = 99;
 
io.on('connection', function (socket) {
	socket.emit('priceUpdate',currentPrice);
	socket.on('bid', function (data) {
		currentPrice = parseInt(data);
		socket.emit('priceUpdate',currentPrice);
		socket.broadcast.emit('priceUpdate',currentPrice);
	});
});

In the first 5 lines I’m just creating the server that Socket.IO will use to send/receive events, then I’m creating a listener to the connection event which will be emitted every time a user connects (we’ll get to that in a moment), you can use the function io.on(event, callback) to create a listener to any event you want, you just need to pass the event as the fist argument and the callback function as the second, when it receives the event the callback will be executed.

In this case when a user connects I’m immediately emitting the event priceUpdate passing the current price, that’s because at this moment the client-side doesn’t have the current price yet, so that’s the first thing we want to send. After that we have to create a listener to the bid event that will update the price and broadcast to the other users. Note that I’m calling socket.emit() and socket.broadcast.emit(), the first one will return the updated price to the user that triggered the event, and the second will do the same to all the other users.

Writing our First Angular 2 Component

Now that we have our server-side ready we can get started with Angular 2, let’s create a folder called app inside public/javascripts/ on our project, that’s where we’re going to put all our Angular 2 code. Now create a file and name it app.component.ts, then paste the following code into it:

import {Component} from 'angular2/core';
 
@Component({
    selector: 'auction-app',
    templateUrl: 'templates/product.html'
})
 
export class AppComponent {
    price: number = 0.0;
    socket = null;
    bidValue = '';
 
    constructor(){
        this.socket = io('http://localhost:8000');
        this.socket.on('priceUpdate', function(data){
            this.price = data;
        }.bind(this));    
    }
 
    bid(){
        this.socket.emit('bid', this.bidValue);
        this.bidValue = '';
    }
}

When declaring a @Component, you have to pass an object containing two attributes selector and templateUrl (or just template), the selector is the name we’re going to use to call our component, in this case it’s auction-app, and the templateUrl is the HTML implementation, you can put your HTML code directly on the object or you can put it in a separated file like I did.

We also have in this code the AppComponent class, that’s kind of the ‘controller’ of our component, in the constructor I’m connecting to the Socket.IO from the server using the method io('http://localhost:8000'), this will emit the connection event we saw before, then I’m creating a listener to the priceUpdate event, the server will emit it right after the connection, remember? When Angular receives the updated price it will assign it to the price variable. This class also contains the bid() function, it will just emit the bid event passing the bidValue.

I forgot to mention that I created the /template folder inside /views, the problem is that our component doesn’t have access to it, to solve this problem we have to make this folder a static route on our server, open your app.js and add this line:

app.use('/templates', express.static(__dirname + '/views/templates/'));

Now let’s take a look on our template, I’ll not show the full HTML code here, just the lines that interact with our AppComponent class.

<h1>$ {{price}}</h1>	        
<input  [(ngModel)]="bidValue" >
<button (click)="bid()">Place Bid</button>

There is not much to explain here, the syntax resembles a lot the first Angular, our input uses the attribute [(ngModel)] to reference the bidValue variable from our class, and the button uses the (click) to call the function bid().

To be able to launch our application we have to create a file called main.ts on the public/javascripts/ folder, just copy/paste the following into the file:

import {bootstrap}    from 'angular2/platform/browser'
import {AppComponent} from './app.component.js'
 
bootstrap(AppComponent);

Finally we can write our index.html, you have already created it in the beginning, remember? It’s located on the /views folder, open it and add the following code:

<html>
  <head>
    <title>Live Auction</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.min.js"></script> 
    <script src="scripts/es6-shim/es6-shim.min.js"></script>
    <script src="scripts/systemjs/dist/system-polyfills.js"></script>
    <script src="scripts/angular2/bundles/angular2-polyfills.js"></script>
    <script src="scripts/systemjs/dist/system.src.js"></script>
    <script src="scripts/rxjs/bundles/Rx.js"></script>
    <script src="scripts/angular2/bundles/angular2.dev.js"></script>
    <script src="javascripts/jquery.js"></script>
    <script src="javascripts/bootstrap.min.js"></script>
    <link href="stylesheets/bootstrap.min.css" rel="stylesheet">
    <link href="stylesheets/portfolio-item.css" rel="stylesheet">
    <script>
      System.config({
        packages: {        
          app: {
            format: 'register',
            defaultExtension: 'js'
          }
        }
      });
      System.import('javascripts/app/main.js')
            .then(null, console.error.bind(console));
    </script>
  </head>
  <body>
    <auction-app>Loading...</auction-app>
  </body>
</html>

Once again we have to edit the app.js file to be able to load the scripts directly from the node_modules folder, add the following line like we did before:

app.use('/scripts', express.static(__dirname + '/node_modules/'));

This file is pretty simple, we have a script that configures System.js to load our application, and in the body we can call our component by the selector we specified before: auction-app.

Now we’re done!! You can run your application by opening your terminal and running the command npm start, the result should similar to the gif in the beginning of this tutorial.

Just leave a comment if you have any problems, I’ll be glad to help!!

How to Execute a .jar File with Node.js Child Processes

You probably have already come across situations where your application had to execute other applications or native commands from the OS. Node.js can easily do that by spawning child processes. To show you how to do that I’m going to give you an example of how to execute a .jar file with node.

First let’s create a very simple java application for us to use in this example, this is the one I’m going to use:

package javaapp;
 
public class JavaApp{
 
    public static void main(String[] args) {
        System.out.println("This is the Java application output!!");
    }
 
}

This class is very simple but it will be enough to demonstrate how child processes work, just copy the code, compile it, and place the jar file into folder of your choice.

Now let’s create a js file containing the following code:

var exec = require('child_process').exec;
var child = exec('java -jar C:/javaApp.jar',
  function (error, stdout, stderr){
    console.log('Output -> ' + stdout);
    if(error !== null){
      console.log("Error -> "+error);
    }
});
 
module.exports = child;

Note how easy it is, first I required the module child_process and then I called the function exec() passing as an argument a native OS command to execute a java file, which is : java -jar C:/javaApp.jar. In the callback function I have 3 variables: error, stdout, stderr, but I’m going to use only the first two. The javaApp.jar output will be stored on the stdout variable, and the errors will be in the error variable, obviously.

To run this code just open the terminal, navigate to your js file location and execute the command:

node app.js

If everything is right you should see the output:

Output -> This is the Java application output!!

Tutorial: Integrating AngularJS with NodeJS

Integrating AngularJS with NodeJS
Integrating AngularJS with NodeJS

I know this tutorial may seem a little bit too basic for a lot of you, but these are two of the most popular javascript frameworks at the moment, as a result of that there are lots of people just getting started with NodeJS and AngularJS, and it’s a very common to see people asking how to integrate both, so this will be a very simple beginner level tutorial in which I’ll give an example to demonstrate how AngularJS and NodeJS can work together.

I’m assuming you have already set your enviroment, so we are going to start by creating our NodeJS project, to do that I’m going to use express, if you don’t have it yet just install via npm with the following command line:

npm install express-generator -g

With express installed simply navigate via terminal to the folder you want your project to be located and execute the command express passing your project name as a parameter, like this:

express myNodeProject

Now that your project is created, you can open it with the text editor of your choice, I’m going to use Sublime Text for this tutorial. When you do it you’ll see that express has already created the basic project structure for you:

Folder Structure
Folder Structure

By default, express uses Jade as the view engine, as you can see in the views folder we already have some jade files, which we are not going use, you can get rid of them later if you want. We’ll need to make some changes here to be able to use angularjs. Let’s begin by opening the file routes/index.js, it contains the following code:

var express = require('express');
var router = express.Router();
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
 
module.exports = router;

That’s the code responsible for rendering and redirecting to the index.jade file, what we need to do here is to change it a little bit and make it redirect to our angularjs index.html file (which we are going to create in a moment). After the changes the code should look like this:

var express = require('express');
var router = express.Router();
var path = require('path');
 
/* GET home page. */
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'views', 'index.html'));
});
 
module.exports = router;

Now we need to create our index.html file, I’m going to put it in the views folder with the jade files. This is how my HTML code looks like:

<!DOCTYPE html>
<html ng-app="angularjsNodejsTutorial">
    <head>
        <title>Integrating AngularJS with NodeJS</title>
        <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.2/angular.js"></script>
        <script src="javascripts/app.js" type="text/javascript"></script> <!-- not created yet -->
    </head>
    <body >
        <div ng-controller="myController">
        </div>
    </body>
</html>

In this file you can use not only AngularJS, but any javascript library you want, if you run your project you’ll see that nodejs is already redirecting to this file, you can now create you angularjs module and start writing some angularjs code as usual.

At this point you are already using angular and node in your application, but they are kind of independent from each other, there are no communication between them. To finish up this tutorial I’m going to show how AngularJS can make a request to NodeJS. But before we do that, we need to come back to the index.js file (the one we just modified) and create a function to return some data, which will be called when we make the request from our angularjs controller, just copy the following code and paste it right above the module.exports on your index.js.

router.get('/data', function(req,res){
	res.json([{"id": 1, "name": "Mymm", "city": "Pantano do Sul"},
        {"id": 2, "name": "Skyble", "city": "Guilmaro"},
        {"id": 3, "name": "Tagfeed", "city": "Gnosjö"},
        {"id": 4, "name": "Realcube", "city": "Jrashen"},
        {"id": 5, "name": "Bluejam", "city": "Zhangjiawo"},
        {"id": 6, "name": "Jayo", "city": "Obonoma"},
        {"id": 7, "name": "Cogidoo", "city": "Sungsang"},
        {"id": 8, "name": "Avavee", "city": "Diawara"},
        {"id": 9, "name": "Tagtune", "city": "Monywa"},
        {"id": 10, "name": "Centimia", "city": "Retkovci"}]);
});

What is happening here is that the router.get function is assigning a function to the url ‘/data’, so when the user types ‘/data’ in the browser, node will call this function, which is doing nothing more than returning a json, it could be getting and handling data from the database, but as I want to keep it simple, a static json will do the job.

Now let’s create our app.js file, as you can see in the HTML code, it’s already referenced there. I’m going to put it on the public/javascript folder.

var app = angular.module('angularjsNodejsTutorial',[]);
app.controller('myController', function($scope, $http) {
    $scope.data = [];
    var request = $http.get('/data');    
    request.success(function(data) {
        $scope.data = data;
    });
    request.error(function(data){
        console.log('Error: ' + data);
    });
});

This is also a very straightforward code, I’m using the function $http.get with the argumentet ‘/data’ to make the request, then I’m assigning the result to $scope.data.

Now we just need to modify a little bit our HTML to make it iterate over our data and show it on the screen, just add this to the div with the ng-controller:

<ul ng-repeat="item in data">
	<li>Name: {{item.name}}, City: {{item.city}}</li>
</ul>

That’s it!! Now just run your project by executing npm start on the terminal and you’ll be able to access the application on your browser by typing localhost:3000, if you did everything right you should see a page with the data from our json.

Hope this tutorial was helpful, till the next one!!