Posts on this Category

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! 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

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.

@angular/cli error when creating project: Unexpected token =

After installing @angular/cli lots of people get this error when trying to create the fist angular project:

SyntaxError: Unexpected token =
   at exports.runInThisContext (vm.js:53:16)
   at Module._compile (module.js:373:25)
   at Object.Module._extensions..js (module.js:416:10)
   at Module.load (module.js:343:32)
   at Function.Module._load (module.js:300:12)
   at Module.require (module.js:353:17)
   at require (internal/module.js:12:17)
   at Object.<anonymous> (C:\Users\a\AppData\Roaming\npm\node_modules\@angular\cli\models\config.js:3:18)
   at Module._compile (module.js:409:26)
   at Object.Module._extensions..js (module.js:416:10)

The solution is very simple, just download and install the newest version of nodejs, this should fix the problem.

How to Load a JSON file in Javascript

In this post I’m going to give you a very simple example of how to read a JSON file and display the data on the page. I’ll be using jQuery in this example, so if you don’t have it on your project don’t forget to add the script.

So let’s get started, first we need a JSON, you probably already have yours, but for this example I’m using this one:


  "id": 1,
  "first_name": "Larry",
  "last_name": "Gebhardt"
}, {
  "id": 2,
  "first_name": "Dorothy",
  "last_name": "Portress"
}, {
  "id": 3,
  "first_name": "Selby",
  "last_name": "Rudolfer"
}, {
  "id": 4,
  "first_name": "Coraline",
  "last_name": "Aspel"}

This file has to be placed somewhere accessible via HTTP, I’m putting it on the same folder my HTML page is located.

jQuery provides the function getJSON for us, it receives two parameters: the JSON url and a callback function to handle the data. Here’s how we can use it:

jQuery.getJSON("data.json", handleJSON);
function handleJSON(result){
   jQuery.each(result, printFields);
function printFields(i, field){
   let row = + " "+field.first_name + " "+field.last_name + " <br>";

First I used jQuery.getJSON to retrieve the data, once we have the result it is passed to the function handleJSON, which is using the jQuery.each to go through the data. Each item from the dataset will be passed to the printFields function, which creates a string with all the fields and append it to an HTML component.

Easy, right? If you run your project now you’ll see the data on your page. If you have any doubts please let me know in the comments.

Error: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https

If you are facing this error it’s because your page is trying to load a local file using file:// or C:/ (you can see it in the URL on your browser). It happened to me one time, that’s because I created a HTML page and simply double-clicked on it to open it on the browser, my page was using a JSON file from the same folder, and when I checked the console this error was there:

Failed to load file:///C:/project/myProject/data.json: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Turned out I needed a webserver for this. The solution was to install one on my computer (WampServer or Lamp will do fine) and host my page on it, this fixed the problem for me.

Tutorial: How to Create Cards UI with CSS & HTML

Cards Demo
Cards Demo

In this short tutorial I’m going to show you how to create cards, they are trending for quite some time now and I thought it would be a good idea to write about them. For this example I’m only using HTML and CSS, my goal here is to just show you how to create the design. Please let me know in the comments if you want another post on how to add animations and some functionalities to it.

So first let’s create our HTML structure, as you can see in the image above, our cards will be composed of an image and a description containing a title and a small text. This is how it should look like in code:

<div class="card">
   <img src="img.jpg" >
   <div class="description">
      <h4 class="title"><b>magna tincidunt et</b></h4> 
         <p class="text">Nam nec lorem eu nibh aliquam egestas non lobortis neque. 
            Ut tristique tortor sem, eget tristique lectus consectetur id. 
            Vivamus sem metus, fermentum in orci ut, rhoncus semper tellus. 
            Praesent eget porttitor metus. Phasellus a ipsum vulputate, cursus massa eu, 
            tincidunt purus. Curabitur auctor vulputate velit</p> 

Don’t forget to pick an image and specify it on the img src attribute. Now we already have our card, it’s not very pretty, though. Let’s add some style to it:

.title, .text{
   font-family: verdana;
   font-size: 12px;
   margin-bottom: 0px;
   margin-top: 5px;
.card {
   box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2);
   transition: 0.3s;
   width: 300px;
   margin: 3px;
   float: left;
.card:hover {
   box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2);
.description {
   padding: 2px 16px;
.card img{

Now just add this CSS to your page. I styled my card this way but feel free to edit this CSS as you like.

That’s it guys! We’ve created a very basic card, as I said before let me know in the comments what functionalities do you want it to have.

How to put Objects on HTML5 sessionStorage/localStorage

HTML5 sessionStorage and localStorage only allows you to store strings, but sometimes it’s very convenient to add more complex values like arrays and objects. Here a simple way to do that:

var array = [];
// Put object on sessionStorage
sessionStorage.setItem('key', JSON.stringfy(array));
// Get object from sessionStorage
var object = JSON.parse(sessionStorage.getItem('key'));

As you can see in the example I’ve just converted my array to a string before storing it in the sessionStorage, then I converted it back to an array when I retrieved it from the sessionStorage. This was a very simple workaraound, hope it helps!

Angular2: How to Pass Callback Functions to a Component

There are lots of situations where it’s useful to pass a function to an angular2 component, for instance, when our component is a dialog and we have to perform an specific task when it closes, or pass the action of one of its buttons, or even events like keypress, resize, mouseover, etc. If you’re reading this tutorial I’m sure you came across your own situation.

As an example I’m going to create a component with just a button, when clicked it will execute the callback function passed to the component, simple as that. Now let’s see the code:

  selector: 'my-component',
  template: `
     <button type="button" (click)="callback()" >Callback Test</button>
export class MyComponent { 
   @Input() callback: Function;

The first thing we have to do is to create a variable so we can assign the callback to it, in this example I’ve declared the variable callback and specified it to be a Function, I’ve also decorated it with @Input(), this will allow us to pass our function to this component. We can use this variable in the template as if it were a regular function, as you can see I’m binding it to the button click event like this: (click)="callback()".

Now let’s see how to pass our function to the component:

  selector: 'my-app',
  template: `
  	<my-component  [callback]="showMessage"></my-component>
export class AppComponent { 
      alert('Callback Test');

First, of course, we must have a function, in this case I’ve created the showMessage(), we can pass it by just adding [callback]="showMessage" to the component on the template, this binds the showMessage function to the callback property we saw on the previous component.

Now if you run the application you’ll see that the showMessage() is called when you click on the button.

Creating an Angular2 Image Gallery

In order to make this tutorial easier for beginners I’m going to start by creating the simplest possible gallery, from there I’m going to develop and add more functionalities to it, which will increasingly make the gallery more complex as we proceed. If you are already familiar and have some experience with angular2 this entire tutorial will be easy for you, but if you’re a beginner it’s really important that you understand every detail from one step before you move on to the next, with that in mind let’s get started!

The first step, of course, is to create an angular2 project, if you don’t know how to create one just follow the instructions from the Angular2 Quickstart.

Before we begin let’s add the bootstrap and jquery scripts to our project, we’re going to need them later, just copy/paste the following code to your index.html.

<script src="" ></script>
<link rel="stylesheet" href="" ></link>
<link rel="stylesheet" href="" ></link>
<script src="" ></script>

Now we can start working on the gallery component, as I said before let’s focus on the basics first, for now all we need is a gallery that shows a list of thumbnails and a dialog with the selected image. This is how it should look like in code:


import {Component, Input} from '@angular/core';
  selector: 'gallery',
  template: `
	<div class="modal fade" id="selectedImageModal" >
	  <div class="modal-dialog" role="document">
	    <div class="modal-content">
	      <div class="modal-body">
	         <img *ngIf="selectedImage" src="{{selectedImage.url}}" >
  	<ul id="thumbnailsList">
  	   <li *ngFor="let image of datasource" >
  	      <img src="{{image.url}}" class="tn"
  		  width="191" height="146"  
  		  data-toggle="modal" data-target="#selectedImageModal"
  styles: [`
  	ul { padding:0; width:780px; margin:20px auto}
  	li { display:inline;}
	   margin:2px 0px;
	   box-shadow:#999 1px 1px 3px 1px; 
	   cursor: pointer 
  	.modal-content {
	    width: 670px !important;
export class GalleryComponent { 
   @Input() datasource;
      this.selectedImage= image;	

Look how simple the template is, we have just two elements: the selectedImageModal and the thumbnailsList. The first one is a Bootstrap dialog with the selected image and the second is the list of thumbnails.

In the GalleryComponent class we have a variable called datasource that provides everything we need to render the component, it is an array of objects containing all the data regarding each image (url, caption, title, etc), all we have to do is to iterate over this dasaset creating an img element for each object on the array, the result will be our thumbnails list.

A really important detail is that the variable datasource is decorated with @Input(), which means that it must be passed to our component as an attribute (I’m going to show how to do that in a moment), this will allow us to reuse the component to show different sets of images across the application.

We also have the selectedImage variable, as the name suggests this variable holds the object with the selected image properties. To select an image the user must click on its thumbnail, when the click occurs the method setCurrentImage will be called thanks to the (click)=setSelectedImage(image) we’ve put on the thumbnails, then a bootstrap dialog will pop up showing the full-sized selected image.

Lastly, I had to do some styling to make this component look like a gallery, one way to use CSS in an angular2 component is to just add the attribute styles to the @Component decorator like I did in this example.

Now we already have a basic gallery, let’s see how we can use it:


import {Component } from '@angular/core';
  selector: 'my-app',
  template: `
    <gallery [datasource]=images></gallery>
export class AppComponent { 
      this.images = [

The usage is very simple, the only thing we have to be concerned here is to pass a datasource to the gallery, in this class I have the images variable that will serve as a datasource, I’m passing it by adding the [datasource]=images to the gallery element on the template.

This is the result so far:

Angular2 Image Gallery - Thumbnails
Angular2 Image Gallery – Thumbnails
Angular2 Image Gallery – Selected Image
Angular2 Image Gallery – Selected Image

Adding the Title and Caption

As I just explained, we have to pass to the gallery component an array of objects containing all the data regarding the images, in our case the variable images from the app.component.ts is our datasource, let’s take a closer look at one of the objects that composes it:


Since the url is the only property we’ve used so far, it’s the only attribute in the object. To be able to show the title and caption we have to modify the datasource by adding these two properties to the objects, this is how it should look like after the modification:

  "title":"Aliquam erat volutpat",
  "caption":"imperdiet imperdiet. Nullam ut ligula vitae arcu vulputate dictum ut quis elit."

Now we can use these new attributes on the gallery.component.ts, when a user clicks on the thumbnail we’re currently showing the selected image with this img element:

<img *ngIf="selectedImage" src="{{selectedImage.url}}" >

Let’s replace the img with a div that contains, besides the image, also the title and caption:

<div class="selectedImage" *ngIf="selectedImage">
   <img src="{{selectedImage.url}}" >
   <div class="caption">

And once again we have to add some styles to the component:

	position:relative }
p {
   -webkit-margin-before: 5px !important;
   -webkit-margin-after: 5px !important;

This is the result:

Image Title and Caption
Image Title and Caption

Adding the Navigation Arrows

After running your application you should’ve noticed that when you select an image there’s no way to select another without closing the dialog first, we can make things much easier for the user by adding navigation arrows, for that to be possible we have to modify the template again by adding two new divs above the caption:

<div class="selectedImage" *ngIf="selectedImage">
   <img src="{{selectedImage.url}}" >
   <div class="arrow-back" (click)=navigate(false)>
   <div class="arrow-forward" (click)=navigate(true)>
   <div class="caption">

The new divs will serve as the navigation arrows, notice that they are calling the function navigate, that’s the function responsible for changing the selected image, let’s see how it works:

   var index = this.datasource.indexOf(this.selectedImage)+(forward ? 1: -1);
   if(index >= 0 && index < this.datasource.length){
      this.selectedImage = this.datasource[index];	

The function receives a boolean as parameter, its value will be false if we click on back and true if we click on the forward arrow. To be able to change the selected image we first have to find out its index, we can easily do that by using indexOf, then we add/subtract 1 from this value and we already have a new index, now we can use this index to get the next/previous image from the datasource and assign it to the selectedImage variable.

Lastly, let’s take care of the styles:

.btn-back, .btn-forward{

This is the result:

Navigation Arrows
Navigation Arrows

Adding Keyboard Shortcuts

I’m not going to go into details about this because I’ve already written a post about keyboard shortcuts, you basically have to add the element host to your component:

host: {'(window:keydown)': 'hotkeys($event)'}

This allows us to call a function on the keydown event, in this case I’m calling the function hotkeys:

      if (event.keyCode == 37){
      }else if(event.keyCode == 39){

In this function I’m just checking the keycode and taking actions accordingly, if the user presses the left arrow (keycode 37) I’m calling navigate(false) and if he presses the right arrow (keycode 38) I’m calling navigate(true).

That’s it guys! I’m going to leave it like that for now, if there are other functionalities you want to add please leave a comment, all suggestions are welcome!

Angular 2 Tutorial: Adding HotKeys (Keyboard shortcuts) to a Component

Arguably hotkeys can substantially increase the usability of an application, the less the users have to touch the mouse the better will be their experience with the application.

Luckily for us there is a very easy way of defining hotkeys on angular2, which is by adding a listener to the host component, we can accomplish this by just adding the element host to the @Component decorator.

Let’s take a look at an example:

import {Component } from '@angular/core';
  selector: 'hotkeys-app',
  host: {'(window:keydown)': 'hotkeys($event)'},
  template: `
  	<button (click)=showMessage()>Hotkey Test</button>
export class AppComponent { 
      if (event.keyCode == 65){
      alert('Hotkey Test');

As you can see I’ve used the element host to add a listener to the window:keydown event, it will call the function hotkeys(event) every time this event occurs, all we have to do now on this function is to determine which key was pressed and take actions accordingly.

As an example I’ve placed a button on the template, let’s suppose we want the action of this button, which is the showMessage() funtion, to execute when the user presses the letter 'a' on the keyboard. On the hotkeys function we have the event parameter containing the keyCode, we have to check this value to see which key was pressed, in this case I’m calling showMessage() when the keycode is 65 (which is code for the letter 'a').

It’s also very common to use combinations as hotkeys, like for example ctrl+a. To do that we just have to change our condition a little bit:

if (event.keyCode == 65 && event.ctrlKey){

The only diference is that besides checking the keyCode I’m also using the event.ctrlKey to check if the ctrl key is pressed.

That’s it guys! Just leave a comment if you have any doubts.

Angular2: Uncaught (in promise): Error: Cannot match any routes: ”

If you’re specifying the routes on your project for the first time you may see the following error on the console when you run it:

core.umd.js:3462 EXCEPTION: Uncaught (in promise): Error: Cannot match any routes: ''ErrorHandler.handleError @ core.umd.js:3462next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ @ Subscriber.ts:190Subscriber._next @ @ @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:196Zone.runGuarded @ zone.js:102_loop_1 @ zone.js:368drainMicroTaskQueue @ zone.js:375ZoneTask.invoke @ zone.js:297
core.umd.js:3467 ORIGINAL STACKTRACE:ErrorHandler.handleError @ core.umd.js:3467next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ @ Subscriber.ts:190Subscriber._next @ @ @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:196Zone.runGuarded @ zone.js:102_loop_1 @ zone.js:368drainMicroTaskQueue @ zone.js:375ZoneTask.invoke @ zone.js:297
core.umd.js:3468 Error: Uncaught (in promise): Error: Cannot match any routes: ''
    at resolvePromise (zone.js:418)
    at zone.js:395
    at ZoneDelegate.invoke (zone.js:192)
    at Object.onInvoke (core.umd.js:6242)
    at ZoneDelegate.invoke (zone.js:191)
    at (zone.js:85)
    at zone.js:451
    at ZoneDelegate.invokeTask (zone.js:225)
    at Object.onInvokeTask (core.umd.js:6233)
    at ZoneDelegate.invokeTask (zone.js:224)ErrorHandler.handleError @ core.umd.js:3468next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ @ Subscriber.ts:190Subscriber._next @ @ @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:196Zone.runGuarded @ zone.js:102_loop_1 @ zone.js:368drainMicroTaskQueue @ zone.js:375ZoneTask.invoke @ zone.js:297
zone.js:344 Unhandled Promise rejection: Cannot match any routes: '' ; Zone: angular ; Task: Promise.then ; Value: Error: Cannot match any routes: ''() Error: Cannot match any routes: ''
    at ApplyRedirects.noMatchError (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:769:20)
    at CatchSubscriber.eval [as selector] (http://localhost:3000/node_modules/@angular/router/bundles/router.umd.js:747:33)
    at CatchSubscriber.error (http://localhost:3000/node_modules/rxjs/operator/catch.js:52:31)
    at MapSubscriber.Subscriber._error (http://localhost:3000/node_modules/rxjs/Subscriber.js:128:26)
    at MapSubscriber.Subscriber.error (http://localhost:3000/node_modules/rxjs/Subscriber.js:102:18)
    at CatchSubscriber.error (http://localhost:3000/node_modules/rxjs/operator/catch.js:55:34)
    at FirstSubscriber._complete (http://localhost:3000/node_modules/rxjs/operator/first.js:143:25)
    at FirstSubscriber.Subscriber.complete (http://localhost:3000/node_modules/rxjs/Subscriber.js:114:18)
    at MergeAllSubscriber._complete (http://localhost:3000/node_modules/rxjs/operator/mergeAll.js:94:30)
    at MergeAllSubscriber.Subscriber.complete (http://localhost:3000/node_modules/rxjs/Subscriber.js:114:18)consoleError @ zone.js:344_loop_1 @ zone.js:371drainMicroTaskQueue @ zone.js:375ZoneTask.invoke @ zone.js:297
zone.js:346 Error: Uncaught (in promise): Error: Cannot match any routes: ''()

To fix this error we have to go to the app.routing.ts, I’m assuming you did something like this to define your routes:

const appRoutes: Routes = [
  { path: 'component1', component: Component1 },
  { path: 'component2', component: Component2 }

The problem is that we have two routes ('/component1' and '/component2'), and when we access the application with the url http://localhost:3000 there’s nothing to tell angular2 which component should be loaded on the page, that’s why it throws an exception.

The solution is to just specify a default route by adding this line:

{ path: '', component: HomeComponent },

Now if we don’t inform any route on the url we’ll be redirected to the HomeComponent.