Build a Skycoin Info Website with Node.js + Express + Skycoin Explorer API iaufmc Follow May 21, 2019 · Unlisted

Skycoin + Node.js + Express

Here we are! The next tutorial on my “Skycoin Explorer API”-Series. This time we will take the important step and make an actual, interactive WebApp using Node.js, Express and the Skycoin Explorer API (also a little bit of HTML, JavaScript and CSS).

Fancy? Let’s build that WebApp!

Please note that I made the code public on GitHub.

Pre-Setup

You will get a lot of information in that tutorial so I try to keep it as compact as possible. The main focus of this tutorial is the API connection via Node.js and Express.

Access to the Skycoin Explorer API . I described this in previous tutorials.

. I described this in previous tutorials. Node.js: Go to the official Node.js website for the download and install Node.js. I already described how to connect Skycoin Explorer API to Node.js in this article.

Setup for this project

Create a folder named sky-app.

Open your console, navigate to that new directory and run npm init (you can skip most options by pressing the enter button. create a server.js file within the sky-app folder — the file inside we will write most of our code.

Running the npm init command within the sky-app folder creates a package.json file

Setup done — let’s start!

Creating the Server using the Express Framework

Express is a minimal and flexible Node.js web application framework. Running a server with Node.js is easy, with Express it is even more simple and faster. Installing Express is just as easy as using it. Just type the following command into your terminal:

npm install — save express

Installing Express is very simple.

Copy the Hello World example from the Express Documentation into the newly created server.js file:

const express = require('express')

const app = express()

const port = 3000 app.get('/', (req, res) => res.send('Hello World!')) app.listen(port, () => console.log(`Example app listening on port ${port}!`))

This app starts a server that listens on port 3000. The app responds with “Hello World” on the root URL (/). Also once we start the app we get a console log that says “Example app listening on port 3000!”

Run the app with the following command:

node server.js

It’s working! You can also open your browser and visit localhost:3000 and you see the “Hello World!” text.

Your WebApp is working!

Creating an index view with EJS (Embedded JavaScript)

We will use EJS to display an HTML file. EJS helps us to dynamically create an HTML file based on variables we pass via JavaScript.

The first step is to install EJS with the following command:

npm install ejs — save

Installing EJS is straight forward and shouldn’t be an issue for you anymore.

and add that code to server.js

app.set('view engine', 'ejs')

We also create a /views/ folder and create an index.ejs file right in that folder.

As I mentioned before we will not go into every detail so please copy the following code into the index.ejs file. With a little HTML knowledge, everybody should understand what the code does:

<!DOCTYPE html>

<html>

<head>

<meta charset=”utf-8">

<title>SkyBalanceApp</title>

<link rel=”stylesheet” type=”text/css” href=”/css/style.css”>

<link href=’https://fonts.googleapis.com/css?family=Open+Sans:300' rel=’stylesheet’ type=’text/css’>

</head>

<body>

<div class=”container”>

<fieldset>

<form action=”/” method=”post”>

<input name=”address” type=”text” class=”ghost-input” placeholder=”Enter a valid Skycoin address” required >

<input type=”submit” class=”ghost-button” value=”Get Coin Amount”>

</form>

<% if(address !== null){ %>

<p><%= address %></p>

<% } %>

<% if(error !== null){ %>

<p><%= error %></p>

<% } %>

</fieldset>

</div>

</body>

</html>

Before we can test we EJS implementation, we go back to the server.js file and remove

app.get(‘/’, (req, res) => res.send(‘Hello World!’))

with

app.get('/', (req, res) => res.render('index'))

Let’s test the WebApp again by running the following command:

node server.js

and once again we check localhost:3000 within our browser:

It’s ugly but it’s visible!

Making your app pretty (CSS)

Let’s be honest: That doesn’t look like a very cool WebApp. So let’s add the design, the CSS file.

Create the directories /public/css and add the empty file style.css to the css folder.

Add the following CSS-code to that file:



Styles from this codepen:

https://codepen.io/official_naveen/pen/rgknI

*/ /*Styles from this codepen:*/ body {

width: 800px;

margin: 0 auto;

font-family: ‘Open Sans’, sans-serif;

}

.container {

width: 600px;

margin: 0 auto;

}

fieldset {

display: block;

-webkit-margin-start: 0px;

-webkit-margin-end: 0px;

-webkit-padding-before: 0em;

-webkit-padding-start: 0em;

-webkit-padding-end: 0em;

-webkit-padding-after: 0em;

border: 0px;

border-image-source: initial;

border-image-slice: initial;

border-image-width: initial;

border-image-outset: initial;

border-image-repeat: initial;

min-width: -webkit-min-content;

padding: 30px;

}

.ghost-input, p {

display: block;

font-weight:300;

width: 100%;

font-size: 25px;

border:0px;

outline: none;

width: 100%;

-webkit-box-sizing: border-box;

-moz-box-sizing: border-box;

box-sizing: border-box;

color: #4b545f;

background: #fff;

font-family: Open Sans,Verdana;

padding: 10px 15px;

margin: 30px 0px;

-webkit-transition: all 0.1s ease-in-out;

-moz-transition: all 0.1s ease-in-out;

-ms-transition: all 0.1s ease-in-out;

-o-transition: all 0.1s ease-in-out;

transition: all 0.1s ease-in-out;

}

.ghost-input:focus {

border-bottom:1px solid #ddd;

}

.ghost-button {

background-color: transparent;

border:2px solid #ddd;

padding:10px 30px;

width: 100%;

font-size: 15px;

min-width: 350px;

-webkit-transition: all 0.1s ease-in-out;

-moz-transition: all 0.1s ease-in-out;

-ms-transition: all 0.1s ease-in-out;

-o-transition: all 0.1s ease-in-out;

transition: all 0.1s ease-in-out;

}

.ghost-button:hover {

border:2px solid #515151;

}

p {

color: #E64A19;

}

Express has to find that file so we have to add the following code to our server.js file:

app.use(express.static('public'));

Restarting the server will give you the following view:

Looks nice but still no functionality!

Clicking on the “Get Coin Amount”-Button will now give you the

Cannot POST /

message. So we start setting up the POST route!

Setting up a POST route

From taking a look at our index.ejs file, you can see that our form is submitting a post request to the / route:

<form action="/" method="post">

With that information, we will add the following code:

app.post('/', function (req, res) {

res.render('index');

})

For that to work we need the body-parser middleware. We have to install that like we did with Express before:

npm install body-parser --save

and add the following code to our server.js file:

const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true }));

With that already setted up we can write our post request:

app.post('/', function (req, res) {

res.render('index');

console.log(req.body.address);

})

We now passed data (our input) from the Client (Browser) to our Server (Node.js / Express). The next step is the actual API request.

The API Call

We are using request for the HTTP request. It can be installed with the following command:

npm install request --save

and add the following code to your server.js:

const request = require(‘request’);

The first step is to get the URL to the API.

We are using this code within our POST request:



let address = req.body.address;

//Edit the NODE-IP!

let url = ` app.post(‘/’, function (req, res) {let address = req.body.address;//Edit the NODE-IP!let url = ` http://NODE-IP/api/v1/balance?addrs=${address}`

Please use a valid Skycoin Node IP address. How you can achieve that locally was explained in my previous articles.

The actual API Call

With that URL we can make the call.

The first thing to do is catching any error:

request(url, function (err, response, body) {

if(err){

res.render('index', {address: null, error: 'Error, please try again'});

Without any error we can proceed to parse the JSON we receive from the request call into a JavaScript object:

else {

let address = JSON.parse(body)

let coins = insertDecimal(address.confirmed.coins);

let hours = address.confirmed.hours.toLocaleString();

let addressText = `Wallet has ${coins} Skycoin and accumulated ${hours} Coinhours!`;

res.render(‘index’, {address: addressText, error: null});

}

As you can see, I am using the insertDecimal function. Reason for that is, that the Skycoin Explorer API returns the value like this:

No separators or decimals

insertDecimals adds the decimals (6) to the coin value:

function insertDecimal(num) {

return(num / 1000000).toFixed(6);

}

And we are done!

Our simple WebApp is done!

Please note that the code is available on GitHub.

Conclusion

Developing WebApps with Node.js and Express is fast and easy. Connection an API like the Skycoin Explorer API is a beautiful way to not just expand your own skill set but also build value around a blockchain ecosystem.

If you liked that article I would love to connect with you via Twitter and if you really like my work I appreciate every donation via SkyCoin: 2BAEQ9tdibebL5XrozW4nQ7ciu4JnFXhcAS