Summary of node short chain principle and function implementation

Time:2021-7-28

Introduction: sometimes we often see a very short website in microblog or some marketing messages. When you open it and check it in the browser, you find that it jumps to a very long website, which is actually a service using a short website. Today, I will simply make a summary and summarize my experience and knowledge combined with a short chain tool I developed before.

catalogue

  • Principle description
  • Method implementation
  • Actual combat drill

Principle description

Short web address, also known as short chain, is a very short web address, which is composed of domain name plus unique ID, letters or numeric characters, probably no more than 10 digits.

Short URL creation

The short web address is created as follows:

  • Obtain parameter website;
  • Query whether there is a short URL returned, and there is no short URL created;
  • When visiting the short website, query the original website of the database as 302;

Short website display

The short web address goes through the following steps from opening to displaying the web page:

  • After opening the short URL, request the short URL server;
  • Read the website address of the database origin according to the unique ID;
  • 302 redirect to the original website;

Visitor information (IP, device information, etc.) may be counted in the middle to collect access data for decision-making;

Short URL function

The benefits of using short web sites are as follows:

  • Short URLs look more comfortable than long URLs;
  • Short web sites are easy to save space and database capacity;
  • The short web address is relatively safe to prevent hackers from directly attacking the original site and reduce DDoS and CC attacks;

Method implementation

Build table

Use the command line to connect to MySQL, and then create ashortWatch.

mysql -h 127.0.0.1 -P 3306 -u demo -p
mysql> use demo;
Database changed
mysql> show tables;
+----------------+
| Tables_in_demo |
+----------------+
| goods          |
| user           |
+----------------+
3 rows in set (0.00 sec)
mysql> CREATE TABLE `short` (
  `id` int(11) NOT NULL COMMENT 'id',
  `sid` varchar(255) COLLATE utf8_ unicode_ Ci not null comment 'short chain code',
  `URL ` varchar (1046) not null comment 'web address',
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_ unicode_ Ci comment = 'short web address';
mysql> ALTER TABLE `short` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT 'id';
mysql> ALTER TABLE `short` ADD PRIMARY KEY(`id`);

Method compilation

First, install an NPM package, and then use thestr10To64as well asshortIdMethod to generate short chain identification code

dbMethods, which have been introduced in the previous articles, will not. Please return to the previous articles to check

npm install xquuid
  • Create short URL
const express = require('express');
const app = express();
const db = require('../model/simple');
const xqsql = require('xqsql');
const xquuid = require('xquuid');

app.post('/s', async (req, res) => {
    let baseUrl = 'http://127.0.0.1:3000/s/';
    let userId = 10;
    let url = req.body.url;
    let urlReg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
    
    if (!url) {
        return res.json({
            code: 101,
            msg: 'get_fail',
            data: {
                Info: "the web address cannot be empty!",
            }
        })
    }

    if (!(urlReg.test(url))) {
        return res.json({
            code: 101,
            msg: 'get_fail',
            data: {
                Info: "web address format error!",
            }
        })
    }
    
    let getSql = xqsql.get('short', {
        type: 'one',
        key: 'url',
        ids: [url],
    }, 'default', 'id,url,sid');
    let getSqlResult = await db(getSql);
    if (getSqlResult.code == 200 &&
    getSqlResult.data.list.length == 0) {
        
        let sid = xquuid.str10To64(xquuid.shortId(userId));
        let shortUrl = `${baseUrl}${sid}`;

        let addParams = [
            {
                sid,
                url
            }
        ]
        let addFields = [
            {
                Name: 'short URL',
                value: 'sid',
                isMust: true
            },
            {
                Name: 'original web address',
                value: 'url',
                isMust: true
            },
        ]

        let addSql = xqsql.add('short', addParams, addFields);
        let addSqlResult = await db(addSql);
        if (addSqlResult.code == 200) {
            return res.json({
                code: 200,
                msg: 'get_succ',
                data: {
                    Info: "created successfully!",
                    url: shortUrl
                }
            });
        } else {
            return res.json(addSqlResult);
        }

    } else {
        return res.json({
            code: 101,
            msg: 'get_fail',
            data: {
                Info: "web address already exists!",
                url: `${baseUrl}${getSqlResult.data.list[0].sid}`
            }
        })
    }

})
  • Visit short URL
//Access short chain
app.get('/s/:sid', async (req, res) => {
    
    let sid = req.params.sid;

    if (!sid) {
        return res.json({
            code: 101,
            msg: 'get_fail',
            data: {
                Info: "short link cannot be empty!",
            }
        })
    }
    
    let getSql = xqsql.get('short', {
        type: 'one',
        key: 'sid',
        ids: [sid],
    }, 'default', 'id,url');
    let getSqlResult = await db(getSql);
    if (getSqlResult.code == 200 &&
    getSqlResult.data.list.length) {
        let url = getSqlResult.data.list[0].url;
        res.redirect(url);
    } else {
        return res.json({
            code: 101,
            msg: 'get_fail',
            data: {
                Info: "short URL does not exist!"
            }
        })
    }
})

Actual combat drill

Long URL search

There are two on the Internet:

http://www.51yuansu.com/sc/vsvhhktgav.html

https://baijiahao.baidu.com/s?id=1704505053721054995&wfr=spider&for=pc

https://mp.weixin.qq.com/s?src=11&timestamp=1625549401&ver=3173&signature=N5D9x59A5A1rhcpac3ujtOEu51niWlSwkna6186uwcvDZl2reuDxNFwv8fQOfOtLuV5XRQkJ6xSVAfWR5lpsSwDRpA3y6CIPLGT5xW21OL2BvJxsA*TvCwkEeX4v1SWr&new=1

Postman create

  • First, open postman, enter a long web address, and send the request to get the following content:

Summary of node short chain principle and function implementation
Summary of node short chain principle and function implementation

Visit short URL

Copy the generated short chain for access

Summary of node short chain principle and function implementation

That’s all for the basic demonstration. If you want a shorter website, you can buy a domain name and resolve it to the node server.

For example:url.meThen buy a server, analyze it, and use itnginxConfigure the reverse proxy.

upstream shortSite {
  server 127.0.0.1:3000 weight=1;
}

server {
  listen 80;
  server_name url.me;
  location / {
    proxy_pass http://shortSite/s/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
  }
}

So try visiting the website above againhttp://url.me/13mm

You can see it’s really much better.

Summary of node short chain principle and function implementation

Well, that’s all for the short chain knowledge. If you find any problems, ask questions in time.