This article was originally written and published by Grape City Technology team

The official website of Grape City, grape city for developers to provide professional development tools, solutions and services, enabling developers.

Front end time in the development of grape city community public 】, there is a feature is need qr code is generated by authorized certification web address, but similar like below Url even see also feel very headache open.weixin.qq.com/connect/oau…

The TWO-DIMENSIONAL code generated by this address is also dense, although it does not affect wechat long press scan code, once the two-dimensional code size shrinks a little, the picture will immediately paste out, leading to the camera directly scan code will be difficult to identify.

In this case, it is natural to think that if you use short links to reduce the length of the URL, the resulting code will be easier to recognize, and the URL will be more beautiful and easy to forward. Available on the market now is the tc weibo n and some third-party tools to generate short link, but these two kinds of tool has some problems, such as: tc n now rule is that there will be a transfer page does not jump straight, and third-party tools as a public platform, sometimes may be because of some bad information, leading to can’t access the entire platform.

Instead, it is better to implement a short link platform by ourselves. It is also very simple to implement a short link platform in principle, and it only takes two parts: 1. Save the correspondence between long and short links. 2. Use the short link to query the long link and redirect it.

I’m using Node and mongodb for efficiency, so let’s get started.

First, let’s create an Express project

express -e demo

change directory: > cd demo install dependencies: > npm install run the app: > SET DEBUG=demo:* & npm start

Then go to the demo directory and install the express necessary dependencies

npm install

Meanwhile, install mongoose and Shortid and Body-Parser we need through NPM

npm install mongoose npm install shortid npm install body-parser

Here is a brief description of the three packages used:

  • In this case, we used mongodb, which was chosen because it was efficient and low overhead, so it was also efficient to execute, although it would be fine if you used another database. Here mongoose is a package of NPM, mainly to provide programs to connect to mongodb and add, delete, check and change the function.
  • By using shortid, you can generate an encoding that specifies that the character is not repeated, which makes it easier to generate an encoding like the scarlet part of xxx.com/ngTsfdgh.
  • Since our API for generating short links uses the POST method, using Body-Parser extends the ability to parse body encoding types.

First, set the connection information for MongoDB

module.exports = { mongo_base_connection_url: ‘mongodb://localhost:27017’, mongo_db: ‘mongodb://localhost:27017/shorturl’, mongo_options: { autoReconnect: true, keepAlive: true, reconnectTries: 50, reconnectInterval: 1000, connectTimeoutMS: 5000000, } } console.log(“Connection local mongo db”);

Database model Definition

Because our corresponding relationship is to query long links through short links, so here we mainly store short links and long links, in addition, you can also add link click statistics and other fields according to their own needs, to facilitate the later statistics.

var mongoose = require(‘mongoose’); var Schema = mongoose.Schema;

var urlSchema = new Schema({ shortUrl: String, longUrl: String });

module.exports = mongoose.model(‘UrlTable’, urlSchema);

Defining express Routes

Because we only have generate and Redirect in the app, there are only two pages to do all the work.

var index = require(‘./routes/index’); var url = require(‘./routes/url’); app.use(‘/’, index); app.use(‘/url’, url);

Generate short link pages

const express = require(“express”); const router = express.Router(); const shortId = require(‘shortid’); const UrlTable = require(‘.. /models/urltable’); const mongoose = require(‘mongoose’); var setup = require(‘.. /dbconfig/db’);

router.post(‘/’, function(req, res, next) { var params = req.body; var url = params.longUrl; shortId.characters(‘ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ^*’) var shortid = shortId.generate(); var objurl = { shortUrl: shortid, longUrl: url}; mongoose.connect(setup.mongo_db, setup.mongo_options); UrlTable.create(objurl, function (err, objurl) { //if (err) console.log(err); res.send(“http://localhost:3000/” + shortid); }); return; });

Specify the range to generate shortId characters and generate:

shortId.characters(‘0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ’)

var shortid = shortId.generate();

Build a compliant data model for the database:

var objurl = { shortUrl: shortid, longUrl: url};

Finally, after connecting to the database and saving, return the short link result to the client:

mongoose.connect(setup.mongo_db, setup.mongo_options);

    UrlTable.create(objurl, function (err, objurl) {

      //if (err) console.log(err);

      res.send(“http://localhost:3000/” + shortid);

});

A short link redirects to the page

const express = require(“express”); const router = express.Router(); const UrlTable = require(‘.. /models/urltable’); const mongoose = require(‘mongoose’); var setup = require(‘.. /dbconfig/db’);

router.get(‘/:shortUrl’, function (req, res, next) { var shortUrl = req.params.shortUrl; mongoose.connect(setup.mongo_db, setup.mongo_options); Urltable.findone ({shortUrl:shortUrl}).then((result) => {// Redirect (result.longurl); })});

module.exports = router;

In order to quickly jump to the page, we use get to receive parameters, this page function is very simple, take the parameter query and jump.

Receive short link code

var shortUrl = req.params.shortUrl;

Connect to the database for query and jump

mongoose.connect(setup.mongo_db, setup.mongo_options);

    UrlTable.findOne({ shortUrl:shortUrl }).then((result) => {

// Error handling to be added

      res.redirect(result.longUrl);

 })

Later you can do some error exception handling, data statistics and so on some enhancements, not to supplement here.

Let’s start testing by enabling the application.

Start the application and test it

npm start

After startup, the default access port is 3000, we first test the short link generation page, here we post a long link parameter named longUrl, data object is:

{” longUrl “:” demo.grapecity.com.cn/spreadjs/Sp…

  

Successfully upgraded to the following short link:

http://localhost:3000/iGE6ZlDmh

We only need to be able to jump to the saved long link by accessing the short link.

  

This test passed, in fact, the amount of code is not large, the principle is very simple. If you have a shorter domain name, the online link will become shorter, more beautiful, so that a short link generation platform belongs to our development is completed. NPM install automatically installs all dependencies. If you have any questions, let me know in the comments section.

Source code download >>