Summary: A simple short-link tutorial.
- Original: Ten minutes for short-link service (Node + Express + MongoDB)
- Author: MudOnTire
Fundebug Copyright shall be owned by the original author when authorized to reproduce.
We have used short links more or less. The so-called short links are short links generated from the long original link url. Visiting short links can jump to the corresponding original link. This is good because: 1. The URL is more beautiful; 2. It is easy to save and disseminate; 3. Some website content is published with word limit and short linksYou can save words.
The principle of short-link implementation is very simple and can be summarized as follows:
- Generate unique short links for each original link
- Save original and corresponding short links in pairs to the database
- When accessing a short link, the web server redirects the target to the corresponding original link
Based on the above ideas, we can also implement a short link generation service by ourselves in minutes.This example uses node + express + mongodb.
1. Initialize the project
(1). Installation depends on:
package.json:
"dependencies": { "config": "^3.2.2", // Read Project Configuration "express": "^4.17.1", // web server "mongoose": "^5.6.9", // Operation mongodb "shortid": "^2.2.14", // Generate a unique Id that does not repeat "valid-url": "^1.0.9" // Determine if the url is formatted correctly }
(2). Increase project configuration:
The base url used to store connection strings and short links for MongoDB.
config/default.json:
{ "mongoURI": "mongodb://localhost:27017/url-shorten-service", "baseUrl": "http://localhost:5000" }
(3). Increase MongoDB connection method
config/db.js:
const mongoose = require('mongoose'); const config = require('config'); const db = config.get('mongoURI'); const connectDB = async () => { try { await mongoose.connect(db, { useNewUrlParser: true }); console.log(`MongoDB Connected to: ${db}`); } catch (error) { console.error(error.message); process.exit(1); } } module.exports = connectDB;
(4). Start express:
index.js:
const express = require('express'); const connectDB = require('./config/db'); const app = express(); // Connect to MongoDB connectDB(); app.use(express.json({ extended: false })); // Routing, set later app.use('/', require('./routes/index')); app.use('/api/url', require('./routes/url')); const port = 5000; app.listen(port, () => { console.log(`Server running on port ${port}`); });
2. Define the database model
We need to save the original link and the corresponding short link to the database. For simplicity, we only need to save a short link code, which can be concatenated using base url and code.
models/url.js:
const mongoose = require('mongoose'); const urlSchema = new mongoose.Schema({ urlCode: String, longUrl: String }); module.exports = mongoose.model('Url', urlSchema);
3. Generate short link encoding
This is a key step for us to achieve, the idea is: Users come in with a long link, and we start with valid-url If the url passed in is valid, an error is returned if it is illegal. If it is valid, we search the database for a record with this long link. If it is, we return the record directly. If it is not, a new record is generated and a corresponding short link is generated.With the help of shortId , we can easily generate a unique code that does not repeat.
routes/url.js:
const epxress = require("express"); const router = epxress.Router(); const validUrl = require('valid-url'); const shortId = require('shortid'); const config = require('config'); const Url = require('../models/url'); router.post('/shorten', async (req, res, next) => { const { longUrl } = req.body; if (validUrl.isUri(longUrl)) { try { let url = await Url.findOne({ longUrl }); if (url) { res.json({ shortUrl: `${config.get('baseUrl')}/${url.urlCode}` }); } else { const urlCode = shortId.generate(); url = new Url({ longUrl, urlCode }); await url.save(); res.json({ shortUrl: `${config.get('baseUrl')}/${urlCode}` }); } } catch (error) { res.status(500).json('Server error'); } } else { res.status(401).json('Invalid long url'); } }); module.exports = router;
4. Visit the short link and jump to the original link
The last step is very simple. When a user visits a short link we generate, we query the corresponding record based on the short link code in the url. If there is a corresponding record, we use the res.redirect method of express to redirect the access to the original link, and if it does not, we return an error.
routes/index.js
const epxress = require("express"); const router = epxress.Router(); const Url = require('../models/url'); router.get('/:code', async (req, res, next) => { try { const urlCode = req.params.code; const url = await Url.findOne({ urlCode }); if (url) { // Redirect to original link res.redirect(url.longUrl); } else { res.status(404).json("No url found"); } } catch (error) { res.status(500).json("Server error"); } }); module.exports = router;
Test it:
Visit short links:
In this way, a simple short link generation service is completed, and the principle and implementation behind what we often think is amazing technology is very simple. I hope this article can inspire you.
Finally, we recommend you to use Fundebug , a very useful BUG monitoring tool~
This article Demo address: https://github.com/MudOnTire/url-shortener-service
About Fundebug
Fundebug Focus on JavaScript, WeChat applets, WeChat games, Alipay applets, React Native, Node.js, and real-time BUG monitoring for Java online applications.Since the official launch of November 11, 2016, Fundebug has handled a total of 2 billion + error events. Payment customers include many brand companies such as Sunshine Insurance, Walnut Programming, Lychee FM, Palm 1 to 1, Weimai, Youth League, etc.Welcome Free Trial!