Making a URL Shortener website using Axios
Tags: javascript, tutorial, webdev, html
Published: 2021-06-24 08:17:14



In this article I will tell you how I made and you can also make a **URL shortener Website**. Check out the result of what we are gonna make: [here](https://vigilant-jepsen-777fa0.netlify.app/).

## Overview
First we will talk about the requirements and dependencies of this project.
In this project we will use **[Axios](https://github.com/axios/axios)** to make a HTTP request (you can also use XML request for Fetch api to do the same),   and [**Hint.css**](https://kushagra.dev/lab/hint/) for hints (not necessary).

Well basically no library mentioned above was **necessary** for this project,  they are here just cause they will make our work easier and will save a lot of time.

**Logic/Working:**
We will add a input tag in which the user will be able to paste his link and a 'Shorten' button. On click of that button a AXIOS request will be fired and then we will pass the  response to the output box. However this seems easy and it is! for a person who knows how to handle API'S response, JSON data and manage errors for multiple cases.
As a beginner you don't have to worry I have covered each and every step mentioned above with good examples.

## Getting started

First of all what we need is a Good Design so that it will also look good. I have already designed a Website for this project here it is:
![design](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dx7jboacyambeea1fkmb.png)

(However I am not a designer so sorry if the design is bad)
In this design there is a heading, a sub-heading,  a input tag for pasting link, a convert button and three boxes for displaying result.
I've used button tags for displaying output (You can also use Input tag).


If you want, you can make the whole website from starting or if you want to follow along or save some time **start with this [codepen](https://codepen.io/devang47/pen/OJpeGMM?editors=1100)** (for basic HTML and CSS) :

## Adding onclick event

First of all we will add a event to 'convert' button i.e. **onclick** and pass a function which will execute when the button is clicked:
```
// function name is 'shorten'
<button type="submit" class="shorten-button font-2" onclick="shorten()">
	Convert
</button>
    
```

Then we will define this function in JS:
```
const shorten = () => {
	console.log('button clicked')
}
```
Don't forget to link the JS file if you are editing outside of codepen.
Then when the button is clicked a message should appear on console.

## Making a request with Axios

Now we will work on the Axios request when  the button is clicked.
Don't know Axios here's a quick intro:
 - **Axios** is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.

- It's syntax is super simple and beginner friendly.

**Basic Axios syntax:**
```
axios.get('API url')
.then((response) => {
	// if the request was Sucessful and no errors were caught
	console.log(response)
})
.catch((error) => {
	// if errors were there.
	console.log(error)
})
```


Before using Axios don't forget to link the Axios package to your HTML file

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.21.1/axios.min.js" integrity="sha512-bZS47S7sPOxkjU/4Bt0zrhEtWx0y0CRkhEp8IckzK+ltifIIE9EMIMTuT/mEzoIMewUINruDBIR/jJnbguonqQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


## Making API call
For the URL shortening we will use a free URl shortening api provider [SHRTCODE](https://shrtco.de/docs/). You can visit the website and read the docs for more info.

This is the main link for calling the API:

 ```
https://api.shrtco.de/v2/shorten?url=YOUR_URL
```


Now we will just add the link to our Axios request in the 'get' method:
```
let longUrl = 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals'

axios
.get(`https://api.shrtco.de/v2/shorten?url=${longUrl}`)
.then((responseData) => {
	console.log(responseData);
})
.catch((err)=> {
	alert('Error check your connectivity or link')
})
```
Here I am using template strings to add the URL to the get method so that we will be able to change it later. 
As this api is free it will take some time to give the response (5 - 10sec), just wait until then. Here is a **[Codepen Example](https://codepen.io/devang47/pen/MWpMZLq?editors=1010)** of a working API call.


After some time we will have the response in the form of **JSON data**, we will store it in a variable for later use or if a Error is caught we will simply alert 'Error check your connectivity or link'.

However we will not give the same link everytime or will change the JS everytime we have  a new link, so we fetch the link from the input tag by value attribute.
```
let  longUrl  =  document.querySelector("#url-box").value;
// we will also declare a variable for later storage of processed url
let shortUrl; 
```
Till now we have the full URL, working JSON request, and processed data.
Now we will get the main Information from that JSON data which is something like this:
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7s7lfxdockt1d57z31ba.png)

The processed URL is `full_short_link` which is inside `result` which is inside of `data`.

 **Well, how to get this URL?**
 We will simple do  `resdata.data.result.full_short_link` to get Processed link  inside of `then`. Here `resdata` is response data from API.
 for ex:
 ```
axios .get(`https://api.shrtco.de/v2/shorten?url=${longUrl}`)
	.then((resdata) => {
		//storing Processed URL in already declared variable
		shortUrl  =  resdata.data.result.full_short_link;
		console.log(shortUrl)
		//check console for Processed URL or errors
	})
	.catch((err) => {
		alert("Error check your connectivity or link");
	});
```

Now half of the work is Done! Congratulations.

## Adding URL display box to HTML

What is left is we have to display it to screen which is not a  big deal.

First of all **Logic**:
We will make a function which will create a element (a div tag) and store it in a variable  then through `.innerHtml` property, We will pass this Markup (as a string) and pass variables (`longUrl` , `shortUrl`) using template strings:
```
` <div class="item">
	<div class="long-url">
		<div class="title font-1">
			Long URL
		</div>
		<button id="long-url" class="font-2">
			${longUrl} 
		 </button>
	</div>
	<div class="short-url">
		<div class="title font-1">
			Short URL
		</div> 
		
		// providing shortUrl variable in value attribute for the copy function⏬
		<button id="short-url" class="font-2" value='${shortUrl}' onclick='copyLink(this)'>
			${shortUrl}
		</button>
	</div>
</div> `
```
```
// compressed version (spaces and tabs removed) because JS will
// give errors on 'tab' and 'enter'

<div class="item"><div class="long-url"><div class="title font-1">Long URL</div> <button id="long-url" class="font-2"> ${longUrl} </button></div><div class="short-url"><div class="title font-1">Short URL</div> <button id="short-url" class="font-2 hint--bottom" aria-label="Click link to Copy" onclick='copy(this)' value='${shortUrl}' onclick='copyLink(this)'>${shortUrl}</button></div></div>
```

 
and then finally this tag will append to the Parent link container. I know this is kinda complicated but this will help you get clear:
```
//Final working:
function  addResult(longUrl, shortUrl) {
	let parentEle = document.querySelector("#shortened-links");
	let data = `<div class="item"><div class="long-url"><div class="title font-1">Long URL</div> <button id="long-url" class="font-2"> ${longUrl} </button></div><div class="short-url"><div class="title font-1">Short URL</div> <button id="short-url" class="font-2" value='${shortUrl}' onclick='copyLink(this)'>${shortUrl}</button></div></div>`;
	
	let  newEle  =  document.createElement("div");
	newEle.innerHTML  =  data;
	parentEle.appendChild(newEle);
}
```
We will pass `longUrl` and `shortUrl` as parameters.

Now we will pass this function in `then` method, which will execute when data is Fetched from API:
```
.then((resdata) => {
	shortUrl  =  resdata.data.result.full_short_link;
	addResult(longUrl, shortUrl);
})
```
and What will happen is this markup will be added to the Html when the data is fetched and as we have already styled their 'class' attributes in CSS, the markup will execute and a processed `item` will show up on the screen.

## CopyLink function
The copyLink function will execute when the short Url box is clicked i.e.
![Copy button](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fofxstx32oa7f1pxsfpj.png)
The function will be:
```
function  copyLink(tag){
	let  text  =  tag.value;
	// copy link to clipboard
	navigator.clipboard.writeText(text);
}
```
The parameter of this function will be the **Tag** and the argument will be `this` keyword. for ex:
```
// usage of this function:
onclick='copyLink(this)'
```
`this` keyword will pass the full button tag through an argument so that we will later be able to use value property in CopyLink func.
**Thats why i've used Button tags for displaying Output** and added value attribute to `shortUrl` tag. 
(you can use input tag also)

Now the Basic working is done and till now this much is done: [here](https://codepen.io/devang47/pen/PoprXOG)
I have added a Hint using [Hint.css](https://github.com/chinchang/hint.css) (just read the documentation it's pretty easy).

## Now about Error Handling and Animations
Now it is upto you how much animations you want to add in this site.
As for error handling we can suppose certain situations in which a Error will occour like 
'What if the input tag is empty and button is clicked' :
```
// we can do something like this:
if (longUrl){
	//if their is value in input tag then only Axios request is sent 
	axios.get()....
}else{
	alert('Enter some data first!!')
}
```

Now If you want to do more customizations in this project that is totally upto you.

If you have any questions ask them in the Comment section and don't forget to leave a like If this post helped you.😊

A post by Devang. Hope it helps!