background

Many H5 activities of the company need to generate two-dimensional code through Qrcode, which will bring some information about users and sharing channels. Finally, html2Canvas will generate posters to carry out some activities of user operation and attracting new users. However, long links through qrcode to generate two-dimensional code, will encounter some models can not be identified by long press, but can be replaced by a short link. So I thought of the short chain service. After converting the long link into a short link through the short chain service, I found that basically all models can recognize the TWO-DIMENSIONAL code and can also smoothly jump to the corresponding link. So they looked for information to build a short chain service, collating information for everyone’s reference.

Initialize the project

1. Install dependencies

package.json

"Dependencies" : {" config ":" ^ "3.2.2, / / read the project configuration" express ":" ^ 4.17.1 ", / / web server "mongoose" : "^ 5.6.9", / / operation directing "shortid" : "^ 2.2.14", / / not to repeat the only generated Id "valid - url" : "^ 1.0.9" / / whether the url format correct}Copy the code

2. Add project configuration

Config /default.json: baseUrl used to store MongoDB connection strings and short links

{ "mongoURI": "mongodb://username:password@hostname:27017/url-shorten-service? authSource=admin", "baseUrl": "" }Copy the code

Username :password Mongodb Username :password

BaseUrl: server IP address + port or domain name

3. Add MongoDB connection methods

The 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;
Copy the code

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, and later set app. Use ('/', the require ('. / routes/index ')); app.use('/api/url', require('./routes/url')); const port = 5000; app.listen(port, () => { console.log(`Server running on port ${port}`); });Copy the code

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, and the corresponding short link can be spliced together with the base URL and the code

Models/url. Js:

const mongoose = require('mongoose');

const urlSchema = new mongoose.Schema({
  urlCode: String,
  longUrl: String
});

module.exports = mongoose.model('Url', urlSchema);
Copy the code

6. Generate short link coding

This is a key step in our implementation, and the idea is: When a user passes in a long link, we first use valid-url to determine whether the url is valid or not. If it is not, an error is returned. If it is valid, we search in the database to see if there is a record of the long link. With shortId, we can easily generate a unique code that does not repeat itself.

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;
Copy the code

7, access the short link to jump to the original link

The final step is very simple. When a user accesses a generated short link, 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, if not, an error is returned.

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 the 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;Copy the code

Install the mongo

Repos. D /mongodb-org-4.4.repo file so that you can install mongodb directly using yum

[mongo - org - 4.4] name = directing a Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.4/x86_64/ gpgcheck = 1 enabled = 1 gpgkey=https://www.mongodb.org/static/pgp/server-4.4.ascCopy the code

2. Install the latest stable version of MongoDB

sudo yum install -y mongodb-org
Copy the code

3. Modify the /etc/mongod.conf configuration file

BindIp =0.0.0.0 # Default is 127.0.0.1, enable remote accessCopy the code

4. Start MongoDB

Run the following command to start the mongodb service: systemctl start mongod. Service Command to stop the mongodb service: systemctl stop mongod. Systemctl status mongod.service Restart mongodb: systemctl restart mongod.serviceCopy the code

5. Set the account password

Name of the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanisms provided by the mechanismsCopy the code

6. Install MongoDB for VS Code connection to view data

PM2 Starts the Node service

pm2 start index.js --name url-shorten-service
Copy the code

Effect of successful startup

Postman Test interface