What are some possible reasons of HTML having <img> as a self-closing tag and <video> not as a self-closing tag?

Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn?

Frontend vs Backend vs Fullstack Web Development - What should you learn? In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?

In Web Development, there's Frontend (JS, HTML, CSS), Backend (PHP, Node.js, DBs, ...) and Fullstack (Everything?) Development. What's the best one?
Limited Offer! Join the Full Node.js Course at 90% off: http://bit.ly/2O0oN6c
Exclusive Discount also available for these courses:

  • React.js: http://bit.ly/36Qm6ww
  • Angular: http://bit.ly/2X0yLZc
  • Vue.js: http://bit.ly/32xDUcj
  • MongoDB: http://bit.ly/34MsB1y
  • CSS: http://bit.ly/2NXtbCZ

How to Validate Phone Number with Javascript

How to Validate Phone Number with Javascript

The validating phone number is an important point while validating an HTML form. In this post we have discussed how to validate a phone number (in different format) using JavaScript

The validating phone number is an important point while validating an HTML form. In this page we have discussed how to validate a phone number (in different format) using JavaScript :

At first, we validate a phone number of 10 digits with no comma, no spaces, no punctuation and there will be no + sign in front the number. Simply the validation will remove all non-digits and permit only phone numbers with 10 digits. Here is the function.

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript phone validation-1

To valid a phone number like
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
use the following code.

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-2

If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code.


function phonenumber(inputtxt)
{
  var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
  if((inputtxt.value.match(phoneno))
        {
      return true;
        }
      else
        {
        alert("message");
        return false;
        }
}

Flowchart:

Flowchart : JavaScript - phone validation-3

Following code blocks contain actual codes for the said validations. We have kept the CSS code part common for all the validations.

CSS Code

 li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

Validate a 10 digit phone number

At first we validate a phone number of 10 digit. For example 1234567890, 0999990011, 8888855555 etc.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head><body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxxxxxxxxx] and Submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-all-numeric-validation.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\d{10}$/;
  if(inputtxt.value.match(phoneno))
  {
      return true;
  }
  else
  {
     alert("Not a valid Phone Number");
     return false;
  }
  }

Flowchart:

Flowchart : JavaScript - phone validation 10 digit

Validate North American phone numbers

Now, let's see how to validate a phone number, either in 222-055-9034, 321.789.4512 or 123 256 4587 formats.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />      
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[xxx-xxx-xxxx, xxx.xxx.xxxx, xxx xxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;      
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Flowchart:

Flowchart : JavaScript - phone validation North America

Validate an international phone number with country code

Now, let's see how to validate a phone number with country code, either in +24-0455-9034, +21.3789.4512 or +23 1256 4587 format.

HTML Code

<!DOCTYPE html><html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript form validation - checking non-empty</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>

<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an Phone No.[+xx-xxxx-xxxx, +xx.xxxx.xxxx, +xx xxxx xxxx] and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="phonenumber(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="phoneno-+international-format.js"></script>
</body>
</html>

JavaScript Code

function phonenumber(inputtxt)
{
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
  if(inputtxt.value.match(phoneno))
     {
	   return true;
	 }
   else
     {
	   alert("Not a valid Phone Number");
	   return false;
     }
}

Thank you for visiting and reading !

How to Validate an IP address using Javascript

How to Validate an IP address using Javascript

IP address validation using javascript

IP address validation

Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (e.g., 0.0.0.0 to 255.255.255.255).

Example of valid IP address

  • 115.42.150.37
  • 192.168.0.1
  • 110.234.52.124

Example of invalid IP address

  • 210.110 – must have 4 octets
  • 255 – must have 4 octets
  • y.y.y.y – the only digit has allowed
  • 255.0.0.y – the only digit has allowed
  • 666.10.10.20 – digit must between [0-255]
  • 4444.11.11.11 – digit must between [0-255]
  • 33.3333.33.3 – digit must between [0-255]

JavaScript code to validate an IP address

function ValidateIPaddress(ipaddress) 
{
 if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(myForm.emailAddr.value))
  {
    return (true)
  }
alert("You have entered an invalid IP address!")
return (false)
}

Explanation of the said Regular expression (IP address)

Regular Expression Pattern :

/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/

This is image title

Note: Last two parts of the regular expression is similar to above.

Syntax diagram - IP-address validation:

Syntax diagram - IP-address validation

Let apply the above JavaScript function in an HTML form.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking IP address/title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an IP address and Submit</h2>
<form name="form1" action="#"> 
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="ValidateIPaddress(document.form1.text1)"/></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="ipaddress-validation.js"></script>
</body>
</html>

JavaScript Code

function ValidateIPaddress(inputText)
 {
 var ipformat = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
 if(inputText.value.match(ipformat))
 {
 document.form1.text1.focus();
 return true;
 }
 else
 {
 alert("You have entered an invalid IP address!");
 document.form1.text1.focus();return false;
 }
 }

Flowchart:

Flowchart : JavaScript - ipaddress validation

CSS Code

li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

Thank for reading !

How to Creat Drag and Drop List with React and HTML

How to Creat Drag and Drop List with React and HTML

What goes into building a drag and drop component in the future?

Creating a Drag and Drop List

This is image title

What goes into building a drag and drop component in 2019?

The drag and drop interaction was invented in the 1970's by Jef Raskin as a part of the Macintosh project. That's 40 years ago! So how come that making things draggable on the web is still so painful? We were recently looking for answers since our component library needs to support a sortable list and slider.

HTML Drag and Drop API

There is an official HTML drag and drop API, it was introduced in the HTML5 standard and it comes with eight different events:

  • drag
  • dragend
  • dragenter
  • dragexit
  • dragleave
  • dragover
  • dragstart
  • drop

Here is a little pop quiz for you. What's the difference between dragexit and dragleave? Not sure? It takes some imagination to implement eight different events for something that could be described by three user actions:

  • pressing the mouse button
  • moving the mouse
  • releasing the mouse button

That is not the only strange thing about this API. Some other "glitches":

  • no support for touch devices (ugh)
  • limited styling options for dragged items
  • the API is wildly inconsistent across browsers

Yes, Internet Explorer 6 is the culprit here. If we don't want to settle with no mobile support and other shortcomings, what else we can do?

(The dragexit event is fired when an element is no longer the drag operation's immediate selection target. The dragleave event is fired when a dragged element or text selection leaves a valid drop target.)

Tracking Basic Actions

Fortunately, there are still good old mouse and touch events:

  • mousedown (touchstart)
  • mousemove (touchmove)
  • mouseup (touchend, touchcancel)

They also nicely translate into our three drag and drop actions.

Mouse/Finger Coordinates

Another information we need is the coordinates of the mouse/finger at any given point. That's very straightforward since all mouse/touch events pass them through. Mouse events:

  • event.clientX
  • event.clientY

Touch events:

  • event.touches[0].clientX
  • event.touches[0].clientY
Measuring Elements

We need to measure things. There is a great API with a horrible name. Let me introduce you Element.getBoundingClientRect. Call it on any element and it returns its dimensions and locations:

{
  "width": 500,
  "height": 100,
  "top": 674,
  "right": 800,
  "bottom": 774,
  "left": 1300
}
Positioning

As user "moves" an item around, we need to keep changing its position to actually create the illusion of moving. The first naive solution could look like this:

position: fixed;
top: 100px;
left: 200px;

As user moves the item, we apply position fixed and keep updating its top and left values. This works reasonably well. However, the better solution is using CSS transforms:

transform: translate(10px, 20px);
transition-duration: 1s;

It's GPU accelerated, requires less work from the browser and we can also combine it with transition-duration to animate it.

Other DOM APIs

There are many other useful DOM APIs to deal with scrolling, container manipulation or optimizing the browser workload:

window.getComputedStyle(ELement);
window.scrollTo(X, Y);
window.pageXOffset;
window.pageYOffset;
window.innerHeight;
Element.contains();
Element.scrollTop;
requestAnimationFrame(() => {});
ReactDOM.createPortal

There is also one very useful React API - Portals.

Portals provide a first-class way to render children into a DOM node that exists outside the DOM hierarchy of the parent component.

Why would we need such a thing? It's the only way to make the positioning of dragged items reliable.

render() {
  return ReactDOM.createPortal(
    <li>Dragged</li>,
    document.body
  );
}

In this example, we "portal" the dragged list item to the bottom of document body. This way the item has no parents and there are no inherited CSS properties that could impact its position (like CSS transforms). You can often see this technique being used for modals or notifications.

The Algorithm

We have all the tools and APIs we need. Now it's time to put it all into a single algorithm.

This is image title

user starts dragging the second item

User clicks on the second item and starts dragging it. We set its visibility to hidden so it preserves the current space occupied by the item and at the same time we portal it to the root. We give it an initial top and left position and as user keeps moving, we update the translate values.

This is image title

User reaches the boundary of the third item

The user reached the boundary of the third item so we want to move the third item to the second position. All we need to do is applying a negative translate Y value. We should also add the transition property to animate it.

So far we didn't change the DOM order of our items. That happens only after the user finishes the drop.

There are many ways how you could go about it but this algorithm is pretty straightforward and works.

Accessibility

What does it mean? You should be able to control our component only through the keyboard and screen reader. There is a set of keyboard shortcuts we implement:

  • tab and shift+tab to focus a item
  • space to lift or drop the item
  • j or arrow down to move the lifted item down
  • k or arrow up to move the lifted item up
  • escape to cancel the lift and return the item to its initial position

We also need to provide audible cues through the screen reader. First, we should describe each item so it's clear that you can move it:

<li aria-roledescription="This is a draggable item. Press space to lift.">
  Item 1
</li>

Then we provide additional messages as the user goes through the interaction:

<div aria-live="assertive" role="log" aria-atomic="true">
  You have lifted item at position 5. Press j to move it down...
</div>

This is called ARIA live region. Whatever you set its content to gets announced by the screen reader. Check this article for more details.

Little Things

There are some little things that you might now even notice but they make the whole interaction nicer. For example, the drop animation. There is none here:

This is image title

No drop animation

On the other hand, we use

transition: 0.3s cubic-bezier(0.2, 1, 0.1, 1);

bellow to make the item fly back which gives user a nice additional feedback:

This is image title

The drop is animated.

And there are many other small interactions like this to consider.

Testing

Any drag and drop library needs to rely on a multiple DOM APIs. If you want to write unit tests, you would have to mock out all of them. What are you even testing at that point? Focusing on end to end tests might be a better solution. With Puppeteer you can write short and descriptive tests. Here we are testing the whole interaction using the mouse:

test('dnd the first item to second position', async () => {
  await page.mouse.move(190, 111);
  await page.mouse.down();
  await page.mouse.move(190, 190);
  await page.mouse.up();
  expect(await getListItems(page)).toEqual([
    'Item 2',
    'Item 1',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
  ]);
});

We just move the mouse around and check the order of DOM elements at the end. The test for keyboard is similar:

test('move the first item to second position', async () => {
  await page.keyboard.press('Tab');
  await page.keyboard.press('Space');
  await page.keyboard.press('ArrowDown');
  await page.keyboard.press('Space');
  expect(await getListItems(page)).toEqual([
    'Item 2',
    'Item 1',
    'Item 3',
    'Item 4',
    'Item 5',
    'Item 6',
  ]);
});
Gotchas

There is a class of bugs that regular tests might not cover. Since we deal with a lot of positioning it's quite easy to misplace some items by a few pixels. We can utilize visual regression testing with jest-image-snapshot. It takes an image (snapshot) of our functioning component, takes another one on the subsequent run and compares them pixel by pixel. If there is any difference, the test fails. Be aware that each OS renders fonts differently. You might need to use docker to keep the tests reliable.

Internet Explorer

Frankly, it would be surprising to open IE for the first time and see everything working. Fortunately, the issues are relatively minor:

  • transform: translate doesn't work for table rows
  • window.scrollBy doesn't exist
  • window.scrollY needs to be replaced by window.pageYOffset
  • window.scroll needs to be replaced window.scrollTo
Safari and Scrolling

The gesture for touch scrolling and drag and drop is exactly the same, so we need to disable the touch scrolling. Luckily for us there is a CSS property just for that:

touch-action: none;

and it works in all browsers. Except Safari. What do you do when CSS fails you? Use more JavaScript! We can e.preventDefault all touch events. However, don't forget to make your event listeners not passive:

document.addEventListener('touchstart', _, {passive: false});

since otherwise the e.preventDefault() calls are ignored by default. This also means you can't use React event system at all - use native events only.

Conclusion

Building a drag and drop web experience is involved but not impossible. You should never compromise on mobile support and accessibility. To ensure that, avoid the HTML5 API and go with mouse/touch events. For positioning, CSS transforms are the right choice. Browsers provide many great APIs like getBoundingClientRect for measuring things. And before you release anything, don't forget to write tests. Puppeteer makes it easy!

Thank for reading! Please share if you liked it!

How to building A Node.js Express API To Convert Markdown To HTML

How to building A Node.js Express API To Convert Markdown To HTML

Learn how to use Node.js and the Express framework in order to create an API endpoint — in the context of building an application that converts Markdown syntax to HTML.

Markdown is a lightweight text markup language that allows the marked text to be converted to various formats. The original goal of creating Markdown was of enabling people “to write using an easy-to-read and easy-to-write plain text format” and to optionally convert it to structurally valid XHTML (or HTML). Currently, with WordPress supporting Markdown, the format has become even more widely used.

The purpose of writing the article is to show you how to use Node.js and the Express framework to create an API endpoint. The context in which we will be learning this is by building an application that converts Markdown syntax to HTML. We will also be adding an authentication mechanism to the API so as to prevent misuse of our application.

A Markdown Node.Js Application

Our teeny-tiny application, which we will call ‘Markdown Converter’, will enable us to post Markdown-styled text and retrieve an HTML version. The application will be created using the Node.js Express framework, and support authentication for conversion requests.

We will build the application in small stages — initially creating a scaffold using Express and then adding various features like authentication as we go along. So let us start with the initial stage of building the application by creating a scaffold.

Stage 1: Installing Express

Assuming you’ve already installed Node.js on your system, create a directory to hold your application (let’s call it “markdown-api”), and switch to that directory:

$ mkdir markdown-api
$ cd markdown-api


Use the npm init command to create a package.json file for your application. This command prompts you for a number of things like the name and version of your application.

For now, simply hit Enter to accept the defaults for most of them. I’ve used the default entry point file as index.js, but you could try app.js or some other depending on your preferences.

Now install Express in the markdown-api directory and save it in the dependencies list:

$ npm install express --save


Create an index.js file in the current directory (markdown-api) and add the following code to test if the Express framework is properly installed:

Const express = require('express');
var app = express();
 
app.get('/', function(req, res){
    res.send('Hello World!');
});
 
app.listen(3000);


Now browse to the URL http://localhost:3000 to check whether the test file is working properly. If everything is in order, we will see a Hello World!’ greeting in the browser and we can proceed to build a base API to convert Markdown to HTML.

Stage 2: Building A Base API

The primary purpose of our API will be to convert text in a Markdown syntax to HTML. The API will have two endpoints:

  • /login

  • /convert

The login endpoint will allow the application to authenticate valid requests while the convert endpoint will convert (obviously) Markdown to HTML.

Below is the base API code to call the two endpoints. The login call just returns an “Authenticated” string, while the convert call returns whatever Markdown content you submitted to the application. The home method just returns a ‘Hello World!’ string.


const express = require("express");
const bodyParser = require('body-parser');
    
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
app.get('/', function(req, res){
    res.send('Hello World!');
});
 
app.post('/login', function(req, res) {
    res.send("Authenticated");
  },
);
 
app.post("/convert", function(req, res, next) {
    console.log(req.body);
    if(typeof req.body.content == 'undefined' || req.body.content == null) {
        res.json(["error", "No data found"]);
    } else {
        res.json(["markdown", req.body.content]);
    }
});
 
app.listen(3000, function() {
 console.log("Server running on port 3000");
});


We use the body-parser middleware to make it easy to parse incoming requests to the applications. The middleware will make all the incoming requests available to you under the req.body property. You can do without the additional middleware but adding it makes it far easier to parse various incoming request parameters.

You can install body-parser by simply using npm:

$ npm install body-parser


Now that we have our dummy stub functions in place, we will use Postman to test the same. Let’s first begin with a brief overview of Postman.

POSTMAN OVERVIEW

Postman is an API development tool that makes it easy to build, modify and test API endpoints from within a browser or by downloading a desktop application (browser version is now deprecated). It has the ability to make various types of HTTP requests, i.e. GET, POST, PUT, PATCH. It is available for Windows, macOS, and Linux.

Here’s a taste of Postman’s interface:

This is image title

To query an API endpoint, you’ll need to do the following steps:

  • 01 Enter the URL that you want to query in the URL bar in the top section;

  • 02 Select the HTTP method on the left of the URL bar to send the request;

  • 03 Click on the ‘Send’ button.

Postman will then send the request to the application, retrieve any responses and display it in the lower window. This is the basic mechanism on how to use the Postman tool. In our application, we will also have to add other parameters to the request, which will be described in the following sections.

Using Postman

Now that we have seen an overview of Postman, let’s move forward on using it for our application.

Start your markdown-api application from the command-line:

$ node index.js

To test the base API code, we make API calls to the application from Postman. Note that we use the POST method to pass the text to convert to the application.

The application at present accepts the Markdown content to convert via the content POST parameter. This we pass as a URL encoded format. The application, currently, returns the string verbatim in a JSON format — with the first field always returning the string markdown and the second field returning the converted text. Later, when we add the Markdown processing code, it will return the converted text.

Stage 3: Adding Markdown Converter

With the application scaffold now built, we can look into the Showdown JavaScript library which we will use to convert Markdown to HTML. Showdown is a bidirectional Markdown to HTML converter written in JavaScript which allows you to convert Markdown to HTML and back.

This is image title

Install the package using npm:

$ npm install showdown


After adding the required showdown code to the scaffold, we get the following result:


const express        = require("express");
const bodyParser = require('body-parser');
const showdown   = require('showdown');
    
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
converter = new showdown.Converter();

app.get('/', function(req, res){
    res.send('Hello World!');
});
 
app.post('/login', function(req, res) {
    res.send("Authenticated");
  },
);
 
app.post("/convert", function(req, res, next) {
    if(typeof req.body.content == 'undefined' || req.body.content == null) {
        res.json(["error", "No data found"]);
    } else {
        text = req.body.content;
        html = converter.makeHtml(text);
        res.json(["markdown", html]);
    }
});
 
app.listen(3000, function() {
 console.log("Server running on port 3000");
});



The main converter code is in the /convert endpoint as extracted and shown below. This will convert whatever Markdown text you post to an HTML version and return it as a JSON document.

...
} else {
        text = req.body.content;
        html = converter.makeHtml(text);
        res.json(["markdown", html]);
    }


The method that does the conversion is converter.makeHtml(text). We can set various options for the Markdown conversion using the setOption method with the following format:

converter.setOption('optionKey', 'value');


So, for example, we can set an option to automatically insert and link a specified URL without any markup.

converter.setOption('simplifiedAutoLink', 'true');


As in the Postman example, if we pass a simple string (such as Google home http://www.google.com/) to the application, it will return the following string if simplifiedAutoLink is enabled:

<p>Google home <a href="http://www.google.com/">http://www.google.com/</a></p>


Without the option, we will have to add markup information to achieve the same results:

Google home <http://www.google.com/>


There are many options to modify how the Markdown is processed. A complete list can be found on the Showdown website.

So now we have a working Markdown-to-HTML converter with a single endpoint. Let us move further and add authentication to have application.

Stage 4: Adding API Authentication Using Passport

Exposing your application API to the outside world without proper authentication will encourage users to query your API endpoint with no restrictions. This will invite unscrupulous elements to misuse your API and also will burden your server with unmoderated requests. To mitigate this, we have to add a proper authentication mechanism.

We will be using the Passport package to add authentication to our application. Just like the body-parser middleware we encountered earlier, Passport is an authentication middleware for Node.js. The reason we will be using Passport is that it has a variety of authentication mechanisms to work with (username and password, Facebook, Twitter, and so on) which gives the user the flexibility on choosing a particular mechanism. A Passport middleware can be easily dropped into any Express application without changing much code.

Install the package using npm.

$ npm install passport


We will also be using the local strategy, which will be explained later, for authentication. So install it, too.


$ npm install passport-local

You will also need to add the JWT(JSON Web Token) encode and decode module for Node.js which is used by Passport:

$ npm install jwt-simple


STRATEGIES IN PASSPORT

Passport uses the concept of strategies to authenticate requests. Strategies are various methods that let you authenticate requests and can range from the simple case as verifying username and password credentials, authentication using OAuth (Facebook or Twitter), or using OpenID. Before authenticating requests, the strategy used by an application must be configured.

In our application, we will use a simple username and password authentication scheme, as it is simple to understand and code. Currently, Passport supports more than 300 strategies which can be found here.

Although the design of Passport may seem complicated, the implementation in code is very simple. Here is an example that shows how our /convert endpoint is decorated for authentication. As you will see, adding authentication to a method is simple enough.


app.post("/convert", 
         passport.authenticate('local',{ session: false, failWithError: true }), 
         function(req, res, next) {
        // If this function gets called, authentication was successful.
        // Also check if no content is sent
        if(typeof req.body.content == 'undefined' || req.body.content == null) {
            res.json(["error", "No data found"]);
        } else {
            text = req.body.content;
            html = converter.makeHtml(text);
            res.json(["markdown", html]);
        }}, 
        // Return a 'Unauthorized' message back if authentication failed.
        function(err, req, res, next) {
            return res.status(401).send({ success: false, message: err })
        });



Now, along with the Markdown string to be converted, we also have to send a username and password. This will be checked with our application username and password and verified. As we are using a local strategy for authentication, the credentials are stored in the code itself.

Although this may sound like a security nightmare, for demo applications this is good enough. This also makes it easier to understand the authentication process in our example. Incidentally, a common security method used is to store credentials in environment variables. Still, many people may not agree with this method, but I find this relatively secure.

The complete example with authentication is shown below.


const express = require("express");
const showdown  = require('showdown');
const bodyParser = require('body-parser');
const passport = require('passport');
const jwt = require('jwt-simple');
const LocalStrategy = require('passport-local').Strategy;
 
    
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
 
converter = new showdown.Converter();
 
const ADMIN = 'admin';
const ADMIN_PASSWORD = 'smagazine';
const SECRET = 'secret#4456';
 
passport.use(new LocalStrategy(function(username, password, done) {
  if (username === ADMIN && password === ADMIN_PASSWORD) {
    done(null, jwt.encode({ username }, SECRET));
    return;
  }
  done(null, false);
}));
 
app.get('/', function(req, res){
    res.send('Hello World!');
});
 
 
app.post('/login', passport.authenticate('local',{ session: false }),
                function(req, res) {
                // If this function gets called, authentication was successful.
                // Send a 'Authenticated' string back.
                res.send("Authenticated");
  });
  
 
app.post("/convert", 
         passport.authenticate('local',{ session: false, failWithError: true }), 
         function(req, res, next) {
        // If this function gets called, authentication was successful.
        // Also check if no content is sent
        if(typeof req.body.content == 'undefined' || req.body.content == null) {
            res.json(["error", "No data found"]);
        } else {
            text = req.body.content;
            html = converter.makeHtml(text);
            res.json(["markdown", html]);
        }}, 
        // Return a 'Unauthorized' message back if authentication failed.
        function(err, req, res, next) {
            return res.status(401).send({ success: false, message: err })
        });
 
 
app.listen(3000, function() {
 console.log("Server running on port 3000");
});


A Postman session that shows conversion with authentication added is shown below.

This is image title

Here we can see that we have got a proper HTML converted string from a Markdown syntax. Although we have only requested to convert a single line of Markdown, the API can convert a larger amount of text.

This concludes our brief foray into building an API endpoint using Node.js and Express. API building is a complex topic and there are finer nuances that you should be aware of while building one, which sadly we have no time for here but will perhaps cover in future articles.

Accessing Our API From Another Application

Now that we have built an API, we can create a small Node.js script that will show you how the API can be accessed. For our example, we will need to install the request npm package that provides a simple way to make HTTP requests. (You will Most probably already have this installed.)

$ npm install request --save


The example code to send a request to our API and get the response is given below. As you can see, the request package simplifies the matter considerably. The markdown to be converted is in the textToConvert variable.

Before running the following script, make sure that the API application we created earlier is already running. Run the following script in another command window.

Note: We are using the (back-tick) sign to span multiple JavaScript lines for the textToConvert variable. This is not a single-quote.


var Request = require("request");
 
// Start of markdown
var textToConvert = `Heading
=======
## Sub-heading
 
Paragraphs are separated
by a blank line.
 
Two spaces at the end of a line  
produces a line break.
 
Text attributes _italic_, 
**bold**, 'monospace'.
A [link](http://example.com).
Horizontal rule:`;
 
// End of markdown
                    
Request.post({
    "headers": { "content-type": "application/json" },
    "url": "http://localhost:3000/convert",
    "body": JSON.stringify({
        "content": textToConvert,
        "username": "admin",
        "password": "smagazine"
    })
}, function(error, response, body){
    // If we got any connection error, bail out.
    if(error) {
        return console.log(error);
    }
    // Else display the converted text
    console.dir(JSON.parse(body));
});


When we make a POST request to our API, we provide the Markdown text to be converted along with the credentials. If we provide the wrong credentials, we will be greeted with an error message.


{
  success: false,
  message: {
    name: 'AuthenticationError',
    message: 'Unauthorized',
    status: 401
  }
}


For a correctly authorized request, the above sample Markdown will be converted to the following:

[ 'markdown',
  `<h1 id="heading">Heading</h1>
  <h2 id="subheading">Sub-heading</h2>
  <p>Paragraphs are separated by a blank line.</p>
  <p>Two spaces at the end of a line<br />
  produces a line break.</p>
  <p>Text attributes <em>italic</em>, 
  <strong>bold</strong>, 'monospace'.
  A <a href="http://example.com">link</a>.
  Horizontal rule:</p>` ]


Although we have hardcoded the Markdown here, the text can come from various other sources — file, web forms, and so on. The request process remains the same.

Note that as we are sending the request as an application/json content type; we need to encode the body using json, hence the JSON.stringify function call. As you can see, it takes a very small example to test or API application.

Conclusion

In this article, we embarked on a tutorial with the goal of learning on how to use Node,js and the Express framework to build an API endpoint. Rather than building some dummy application with no purpose, we decided to create an API that converts Markdown syntax to HTML, which anchors or learning in a useful context. Along the way, we added authentication to our API endpoint, and we also saw ways to test our application endpoint using Postman.