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.

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:

data.json

[{"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 (
        <ul>
        {
          data.map(function(movie){
            return <li>{movie.id} - {movie.title}</li>;
          })
        }
        </ul>
    );
  }
}
 
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.

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:

data.json

[{
  "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.id + " "+field.first_name + " "+field.last_name + " <br>";
   jQuery("div").append(row);
}

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.

Angular2: How to Sort a JSON Dataset by Field

To be able to sort an array we don’t need anything specific from angular2, it can be accomplished just by using regular javascript, more specifically, we have to use the function sort() from the Array object, let’s see an example:

someArray.sort(function(a, b){
    if ( a.someField < b.someField )
        return -1;
    if ( a.someField > b.someField )
        return 1;
    return 0;
});

The sort function receives a comparator as a callback, which will compare each element of the array with the others (two at a time) in order to sort the dataset, the arguments a and b are the two objects being compared, we can implement this method and compare the objects as we want, but it must always return 1 if a is greater than b, -1 if b is greater than a or 0 if they are equal.

This is how it looks in an angular2 class:

export class AppComponent { 
     names = [{"id": 1,"first_name": "Jason","last_name": "Martin"}, 
     {"id": 2,"first_name": "Douglas","last_name": "Holmes"}, 
     {"id": 3,"first_name": "Randy","last_name": "Woods"}, 
     {"id": 4,"first_name": "Thomas","last_name": "Castillo"}, 
     {"id": 5,"first_name": "Ryan","last_name": "Butler"}, 
     {"id": 6,"first_name": "Jose","last_name": "Turner"}, 
     {"id": 7,"first_name": "Carl","last_name": "Taylor"}, 
     {"id": 8,"first_name": "Brandon","last_name": "Mendoza"}, 
     {"id": 9,"first_name": "Willie","last_name": "Ross"}, 
     {"id": 10,"first_name": "Howard","last_name": "Montgomery"}]
 
     ngOnInit(){
	this.names.sort( function(name1, name2) {
	    if ( name1.first_name < name2.first_name ){
	    	return -1;
	    }else if( name1.first_name > name2.first_name ){
	        return 1;
	    }else{
	    	return 0;	
	    }
	});
     }
}

In this example I’m using the sort function on the ngOnInit() to order my array of names by the field first_name, but I could be sorting by any other field if I wanted, or even more than one field.

Alternatively, we can use angular2 pipes to sort datasets, this is how we can implement one:

@Pipe({name: "sortBy"})
export class SortPipe {
  transform(array: Array<string>, args: string): Array<string> {
    array.sort((a: any, b: any) => {
	    if ( a[args] < b[args] ){
	    	return -1;
	    }else if( a[args] > b[args] ){
	        return 1;
	    }else{
	    	return 0;	
	    }
    });
    return array;
  }
}

One of the differences is that by doing this way we can sort an array directly on the *ngFor:

*ngFor="let name of names | sortBy : 'first_name'"

I personally think that this is a much better option than the previews one, by using a pipe you can sort any array you want without worrying about implementing the comparator function every time.

For more details about pipes click here.

How to Load a JSON file in Angular2

Angular2 makes it very easy for us to load data from JSON files, we can do it by simply making a http request. Now let’s see how we can do that.

To be able to make Http requests we first have to import the HttpModule on the app.module.ts, once you’ve done that your code should look like this:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule }      from '@angular/http';
import { AppComponent }   from './app.component';
 
@NgModule({
  imports:      [ BrowserModule, HttpModule ],
  declarations: [ AppComponent],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Next you have put your JSON file in a location accessible via Http, you can put it directly on the root folder of your project if you want, I’m going to create a new folder called /data to keep the files organized.

Now you can load you file using http.get() like I did in the constructor:

import {Http} from '@angular/http';
import { Component } from '@angular/core';
 
@Component({
  selector: 'my-app',
  template: ``,
})
export class AppComponent { 
 
    data;
 
    constructor(private http:Http) {
        this.http.get('data/data.json')
                .subscribe(res => this.data = res.json());
    }
 
}

Note that I’ve used the subscribe() function here, it receives another function responsible for handling the response, in this case I’m just assigning it the the data variable.

Very simple, right? I’ve used Angular 2.0.0-rc.6 version for this tutorial, if you are using a different version this may not work for you.