In today's digital age, sharing long URLs can be awkward and unattractive. A URL shortener is a handy tool that transforms lengthy URLs into short, easy-to-share links. In this blog post, we'll walk through building a simple URL shortener using HTML, CSS, and JavaScript, with a backend powered by Node.js and Express. Let's get started!
Setup Of The Project
Step - 1:
First, Create A new Directory for the project and Initialize it with the npm.
command:
mkdir Url-shortener
cd Url-shortener
npm init -y
Install Required Packages:
Step - 2:
Create a file name server.js and setup the Express server
In this server.js file create an .env file to handle the server ports.
And also create a db.js File to connect to the Mongodb Using the mongoose
Step - 3:
Define Routes
Add routes for creating and retrieving shortened URLs in
Server.js
:Create two folders models and routes
In the models folder create a file shortUrlModel.js and in the routes folder create two files apiRouter.js and mainRouter.js these both defines the routes for creating and retrieving the shortende URLs.
Step - 4:
- Checking whether the url is running or not
2. In the post Request we have declare a token id for Url-Shortening
3. create a document in the Mongodb and connect this with the site which we want to shorten the url
Run the server.js:
Output:
open the browser and type the url : http://localhost:10000/SNWdP
Conclusion:
Building a URL shortener is an excellent project for honing your web development skills. By combining HTML, CSS, and JavaScript for the frontend with Node.js and Express for the backend, you create a practical and valuable tool. This project covers essential aspects of web development, including form handling, database interaction, and URL redirection.