html url shortener "#/" nodejs
- User
html url shortener "#/" nodejs
- Assistant
Creating a basic URL shortener using Node.js with HTML frontend and using a hash (
#) in the URL for client-side routing is a common approach for single-page applications. Below I'll provide a simple example to illustrate how you can:- Create a Node.js backend that generates short URLs.
- Serve a simple HTML page that uses the hash (
#) for client-side routing. - Map short URLs to original URLs on the server.
Overview
- Backend: Node.js + Express (simple REST API to create short URLs and redirect).
- Frontend: HTML + JavaScript that updates the URL hash and calls backend API.
- In-memory store for simplicity (no database).
Step 1: Setup Node.js and Express Backend
Create a new folder, e.g.,
url-shortener, and inside create:package.json{ "name": "url-shortener", "version": "1.0.0", "main": "server.js", "license": "MIT", "scripts": { "start": "node server.js" }, "dependencies": { "express": "^4.18.2", "body-parser": "^1.20.2", "nanoid": "^4.0.0" } }Run:
npm install
server.jsconst express = require('express'); const bodyParser = require('body-parser'); const { nanoid } = require('nanoid'); const app = express(); const PORT = process.env.PORT || 3000; // In-memory store for URLs: { shortId: originalUrl } const urlDB = {}; app.use(bodyParser.json()); app.use(express.static('public')); // API: Shorten URL app.post('/api/shorten', (req, res) => { const { url } = req.body; if (!url || !url.startsWith('http')) { return res.status(400).json({ error: 'Invalid URL, must start with http/https' }); } const id = nanoid(6); // generate 6-char id urlDB[id] = url; res.json({ shortId: id }); }); // Redirect short URL to original app.get('/:id', (req, res) => { const id = req.params.id; const url = urlDB[id]; if (url) { return res.redirect(url); } else { return res.status(404).send('URL not found'); } }); app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
Step 2: Create Frontend with Hash Routing
Create a folder
public, and inside add:index.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>URL Shortener</title> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 2em auto; } input, button { padding: 0.5em; font-size: 1em; } #result { margin-top: 1em; } </style> </head> <body> <h1>Simple URL Shortener</h1> <div id="shorten-form" style="display: none;"> <input type="text" id="url-input" placeholder="Enter a URL (must start with http)" size="50" /> <button id="shorten-btn">Shorten</button> <div id="result"></div> </div> <div id="redirect-message" style="display: none;"> Redirecting to URL... </div> <script> const shortenForm = document.getElementById('shorten-form'); const redirectMessage = document.getElementById('redirect-message'); const urlInput = document.getElementById('url-input'); const shortenBtn = document.getElementById('shorten-btn'); const resultDiv = document.getElementById('result'); function renderForm() { shortenForm.style.display = 'block'; redirectMessage.style.display = 'none'; resultDiv.innerHTML = ''; urlInput.value = ''; } function renderRedirect() { shortenForm.style.display = 'none'; redirectMessage.style.display = 'block'; } // Handle shortening URL shortenBtn.addEventListener('click', async () => { const url = urlInput.value.trim(); if (!url.startsWith('http')) { resultDiv.innerText = 'URL must start with http or https'; return; } resultDiv.innerText = 'Shortening...'; try { const res = await fetch('/api/shorten', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ url }), }); const data = await res.json(); if (data.error) { resultDiv.innerText = 'Error: ' + data.error; return; } const shortUrl = window.location.origin + '/#/' + data.shortId; resultDiv.innerHTML = `Short URL: <a href="${shortUrl}">${shortUrl}</a>`; } catch (e) { resultDiv.innerText = 'Error contacting server'; } }); // Handle hash routing window.addEventListener('hashchange', () => { const hash = window.location.hash; if (hash.startsWith('#/')) { const id = hash.slice(2); if (id) { // Redirect to original URL by calling backend /:id renderRedirect(); window.location.href = '/' + id; } else { renderForm(); } } else { renderForm(); } }); // Initial check if (window.location.hash.startsWith('#/')) { const id = window.location.hash.slice(2); if (id) { renderRedirect(); // Redirect immediately window.location.href = '/' + id; } else { renderForm(); } } else { renderForm(); } </script> </body> </html>
How it works
- User opens
/which shows the form. - User enters a URL, clicks "Shorten".
- JS sends POST
/api/shortento get a short ID. - The short URL is shown as
http://localhost:3000/#/abc123 - When user visits the short URL, the client sees hash
#/abc123and redirects browser to/abc123 - Server redirects
/abc123to the original URL.
Run
node server.jsVisit
http://localhost:3000
Summary
This example uses client-side hash routing (
#/shortId) which is convenient for SPAs that don't require server-side routing of the/shortIdpath directly in the frontend app — the backend handles the redirect.If you want the short URLs themselves to look like
/abc123without hash, you'd only use server-side routing and no hash routing on frontend.
If you want me to provide additional features: persistent storage with a DB, nicer UI, or explanation, feel free to ask!