DEV Community

loading...
Cover image for Making a URL Shortener website using Axios

Making a URL Shortener website using Axios

Devang Saklani
Freelance Front-end developer
・6 min read

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.

Overview

First we will talk about the requirements and dependencies of this project.
In this project we will use Axios to make a HTTP request (you can also use XML request for Fetch api to do the same), and Hint.css 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

(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 (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>

Enter fullscreen mode Exit fullscreen mode

Then we will define this function in JS:

const shorten = () => {
    console.log('button clicked')
}
Enter fullscreen mode Exit fullscreen mode

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)
})
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Making API call

For the URL shortening we will use a free URl shortening api provider SHRTCODE. 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
Enter fullscreen mode Exit fullscreen mode

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')
})
Enter fullscreen mode Exit fullscreen mode

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 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; 
Enter fullscreen mode Exit fullscreen mode

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

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");
    });
Enter fullscreen mode Exit fullscreen mode

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> `
Enter fullscreen mode Exit fullscreen mode
// 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>
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
})
Enter fullscreen mode Exit fullscreen mode

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
The function will be:

function  copyLink(tag){
    let  text  =  tag.value;
    // copy link to clipboard
    navigator.clipboard.writeText(text);
}
Enter fullscreen mode Exit fullscreen mode

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)'
Enter fullscreen mode Exit fullscreen mode

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
I have added a Hint using 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!!')
}
Enter fullscreen mode Exit fullscreen mode

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!

Discussion (0)