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.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);
module.exports = app;

Now let’s create our first route, I’m putting it at the end, right above the module.exports line:'/test', (request, response) => {

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 => { 
}).catch(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();

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.

How to use Bootstrap in a Reactjs project

Styling is a little bit different in Reactjs, so you cannot use Bootstrap in a traditional way. In this tutorial I’m going to show you an easy way to add Bootstrap to a Reacjs project. As we can’t use the traditional Bootstrap we have to use another version called React-Bootstrap, it’s basically the same framework, but it was rebuilt so we can use it with React. You can install it in your project via:

npm install --save react-bootstrap

React-bootstrap doesn’t come with the CSS, so you have to add it manually to your index.html:

<link rel="stylesheet" href="">

Ok, we’re already done with the setup. Now we’re ready to import the components and start using them. To give you an example of how to do that I’m going to import the Bootstrap FormControl component and use it in my project.

import React, { Component } from 'react';
import FormControl from '../node_modules/react-bootstrap/lib/FormControl';
class Field extends Component {
  render() {
    return (
        <FormControl type="text"/> //<-- This is equivalent to <input class="form-control" type="text"/>

Note that in line 2 I’m importing the FromControl from the react-bootstrap folder inside the node_modules. I recommend you to check this folder so you can see all the components you have available. If you run your project now you’ll see the bootstrap input you’re used to.

That’s pretty much it, of course not every react-boostrap component will be as simple as this one, so if you have any doubts on how to use them please let me know in the comments.

Reacjs Error: The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + ’em’}} when using JSX

This error occurs when you try to pass regular CSS strings to the style attribute of an HTML element. In React, the styling is different, instead of an string the style attribute expects an object.

So instead of doing this:

<p style="font-size: 12px; color: black" >text</p>

you should do this:

var pStyle {
   fontSize: '12px',
   color: 'black',
<p style={pStyle} >text</p>

Note that the name of some CSS attributes are a little bit different in React, you should always write them camelCased. As you can see in this example the font-size attribute became fontSize.

That’s pretty much it! Hope it helps.

Reactjs Error: Adjacent JSX elements must be wrapped in an enclosing tag

This is a very common Reactjs error, specially for beginners. If you are getting this error you code probably looks like this:

class App extends Component {
  render() {
    return (

The problem is that your render function is returning two elements, it’s equivalent to adding two return statements to your function, and reactjs won’t allow that.

The solution is very simple, you just have to add an enclosing tag as described in the error message. After this modification the code should look like this:

class App extends Component {
  render() {
    return (

As you can see I’ve added a div as an enclosing tag, now the function is returning only one element. This this should fix the problem, but if it doesn’t 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: How to create an Overlay Panel

Overlay Panel
Overlay Panel

Today I’m doing another webdesign tutorial, this time I’m going to be showing you how to create an overlay panel. There are lots of ways you can use it, one of then is as a dialog, like in image above.

So let’s start with the HTML structure:

<div class="overlay_panel">
	<b>Overlay Panel</b>
	<p>Phasellus vel metus iaculis mauris condimentum imperdiet. Praesent feugiat fermentum 
           aliquet. Mauris porttitor, nisl at eleifend sodales, eros ex eleifend arcu, sit amet 
           molestie dui neque non tellus. In hac habitasse platea dictumst. Nunc quis accumsan 
           nisi. Donec at congue ante. Morbi laoreet a leo eget pharetra. Aenean scelerisque c
           onsequat vehicula. Sed quis condimentum arcu. Quisque pulvinar mauris eget sapien so
           llicitudin, vitae blandit lectus pellentesque. Nullam at nibh rhoncus, feugiat tellu
           s ut, iaculis velit.
	<a href="#" onclick="hide()">OK</a>

The only thing that matters here is the div with the overlay_panel class, you can put anything you want inside it. As an example I’ve put a title, a text and an ok button.

Now let’s do the styling:

.overlay_panel {
    position: fixed;
    top: 0; 
    left: 0;
    right: 0;
    bottom: 0;
    margin: 100px auto;
    width: 50%;
    display: none;
    border-radius: 2px;
    text-align: justify;
    background-color: white;
    color: #333;
    padding: 20px;
    box-shadow: 2px 2px 10px 2px #333;
.overlay_panel a{

You can adjust the width, height, color and pretty much everything else as you like, but you should keep the display: none to make it hidden by default, and also the position: fixed, which will position your panel in front of your page content.

Lastly, this is how to show/hide it:

function show() {
    document.getElementsByClassName("overlay_panel")[0].style.display = "block";
function hide() {
    document.getElementsByClassName("overlay_panel")[0].style.display = "none";

These two functions just switches the display from none to block, and vice versa. Note that I’ve used the function getElementsByClassName to get the element, but it returns an array, so I had to specify the index to access my element. Alternatively, you could use getElementsById function, which returns only one element.

How to load a JSON file in Reactjs

It’s really easy to load data from a JSON file in React. In this post I’m going to show you how you can do that. First, of course, we need a JSON file, you probably already have yours, but I’m using this movies list for this example:


[{"id": 1,"title": "Child Bride"}, 
{"id": 2, "title": "Last Time I Committed Suicide, The"}, 
{"id": 3, "title": "Jerry Seinfeld: 'I'm Telling You for the Last Time'"}, 
{"id": 4, "title": "Youth Without Youth"}, 
{"id": 5, "title": "Happy Here and Now"}, 
{"id": 6, "title": "Wedding in Blood (Noces rouges, Les)"}, 
{"id": 7, "title": "Vampire in Venice (Nosferatu a Venezia) (Nosferatu in Venice)"}, 
{"id": 8, "title": "Monty Python's The Meaning of Life"}, 
{"id": 9, "title": "Awakening, The"}, 
{"id": 10, "title": "Trip, The"}]

Now we have to place this file somewhere inside our project folder, it doesn’t necessarily need to be on the project, but it must be somewhere accessible via Http.

Once you have the path to your file you can load it this way:

import React, { Component } from 'react';
import data from './data.json';
class App extends Component {
  render() {
    return (
            return <li>{} - {movie.title}</li>;
export default App;

Note that all I had to do was to import the file in line 2, then the data was already ready for me to use on the data variable. Lastly, to show you how to use this variable I’ve made this component iterate over the dataset and display it on a list.

Easy right! 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 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 Server

The next step is to add to the project:

npm install --save 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 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('').listen(server);
io.set("origins", "*:*");
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 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 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.


import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
  selector: 'admin-component',
  templateUrl: './app.adminComponent.html'
export class AdminComponent {
   constructor(private socket: Socket) {}
      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>

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


import { Component } from '@angular/core';
import { Socket } from 'ng-socket-io';
  selector: 'user-component',
  template: ''
export class UserComponent {
   constructor(private socket: Socket) { 
      socket.on('new notification', function(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 },
  imports: [
    //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';
  selector: 'app-root',
  template: `
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.

How to add to an Angular application

Lots of people get confused when trying to use with Angular, some developers just add the script to the HTML and start using it, even though it works I don’t recommend doing this way, let me show you the right way to use it with Angular.

After creating your angular project install ng-socket-io via:

npm install ng-socket-io --save

This is an Angular specific module. After the installation is complete you have to configure in your app.module.ts, you basically just have to add the imports and inform the server url:

import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';
const config: SocketIoConfig = { url: 'http://localhost:8000', options: {} };   <-----------------
  declarations: [
  imports: [
    SocketIoModule.forRoot(config)     <-----------------
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

Next, open the tsconfig.json and add the “include” attribute at the end, this will prevent some errors when building your project. Make sure the file looks like this:

  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
    "lib": [
  "include": [

That’s it! Now you just have to import it to your component and start using it:

import { Socket } from 'ng-socket-io';
//usage example
constructor(private socket: Socket) {