专业的短链接生成工具
链接域名
短网址有效期
node js 生成短链接源码
更新时间:2025-5-2 22:07:48 作者:爱短链
应用场景:发送短信时,可能由于参数问题导致链接过长,超过了邮件的字数限制,所以链接要尽量短
原则
生成唯一标识符来标记链接并将其存储在数据库中。比如
{ fullUrl: 'https://www.aifabu.com', shortUrl: 'jgXqZSu8W' }
即根据shortUrl的值,找到它的fullUrl,然后重定向跳转。
实施
使用新浪API生成URL短链接
js var convertStr = encodeURIComponent(urlStr); //转码 var appkey = 'xxx'; getShortUrl(convertStr); function getShortUrl(urlStr) { $.ajax({ type: 'GET', url: 'http://api.t.sina.com.cn/short_url/shorten.json?source=' + appkey + '&url_long=' + urlStr, //source为新浪appkey dataType: 'JSONP', json: 'callback', data : {}, success: function(r) { return r[0].url_short; //生成短链接 } }); }
nodejs 生成短链接
1.快速创建项目
新建文件夹 mkdir shortUrl
初始化项目 npm init -y
安装依赖请参考package.json,npm i -S express
重建根目录下的app.js文件
修改package.json的运行命令,在脚本中添加“start”:“node app.js”;
编写 app.js 生成短链接
const express = require('express');常量应用程序 = 快递(); app.get('/', async (req, res) => { res.send('hello world') });应用 .listen(5000)
运行npm start,打开页面locahost:5000,可以看到hello world表示项目运行成功。大框架已经存在,接下来需要修改。
2.创建数据库
数据库的操作类似,这里以sqlite3为例。因为不需要在本地安装客户端,所以可以使用,比较方便。为了简化操作,数据库操作额外安装了sequelize。
更改根目录下的文件夹db,并更改该文件夹下的index.js、shortUrl.js文件
安装依赖 npm i -S shordid sqlite3 sequelize
首先我们来写shortUrl.js,
// shortUrl.js const shortId = require('shortid'); // 生成 短链接 的代码 module.exports = (sequelize, DataTypes) => { const ShortUrlModel = sequelize.define(' ShortUrlModel', { full: { type: DataTypes.STRING }, short: { type: DataTypes .STRING, defaultValue: shortId.generate }, }) ShortUrlModel.associate = function (models) { } return ShortUrlModel }
// config.js const path = require('path'); module.exports = { 数据库:{ 数据库:process.env.DB_NAME || 'shorturl',用户:process.env.DB_USER || 'shorturl',密码:process.env.DB_PASS || 'shorturl',选项:{方言:process.env.DIALECT || 'sqlite',主机:process.env.HOST || 'localhost',存储:path.resolve(__dirname, './shorturl.sqlite') } } }
然后,编写 index.js
// index.js const {Sequelize} = require('sequelize'); const config = require('../config.js');常量 fs = 要求('fs');常量路径 = 要求(“路径”);常量 db = {}; const sequelize = new Sequelize(config.db.database, config.db.user, config.db.password, config.db.options); // 把数据放到Model export的文件夹中,这样就不用自动一一写入 fs .readdirSync(__dirname) .filter((file) => file !== 'index.js' ) .forEach ((file) => { const model = require(path .join(__dirname, file))(sequelize, Sequelize.DataTypes) db[model.name] = model }) // 我复制进去了,不知道这是什么意思,当我知道它时,我会添加 Object.keys(db) .forEach(function (modelName) { console.log(Object.keys(db)) if ('associate' in db[modelName]) { db[ modelName].associate(db) } }) db.sequelize = sequelize; db .Sequelize = 续集;模块.exports = db;
3. 重写 app.js 生成短链接
const express = require('express');常量应用程序 = 快递(); const {sequelize, ShortUrlModel} = require('./db'); // sequelize 连接数据库 sequelize.sync({force: true} ) // force: true,每次项目初始化都会清除数据。then(() => { console.log(`数据库创建` ) }) // 设置模板引擎 app.set('view engine', 'ejs'); app.use(express.urlencoded({extended: false })); // 获取请求的参数 app.get('/', async (req, res) => { // 获取所有要渲染的链接 const shortUrls = await ShortUrlModel.findAll(); res.render('index', {shortUrls}); }); app.post('/shortUrls', async (req, res) => { // 提交链接数据并保存 await ShortUrlModel.create(req.body); res.redirect('/'); }) app.get( '/:short', async(req, res) => { // 根据代码短链接找到这条数据,数据中有完整的链接 const shortUrl = await ShortUrlModel.findOne({ where: { short: req.params.short } }); // 获取完整链接后,重定向 res.redirect(shortUrl.full) }) app.listen(5000)
4. 写视图/index.ejs
完整网址 | 短网址 |
---|---|
<%= shortUr l.full l %> | <%= shortUrl.short %> |
URL Shrinker
Url收缩<% shortUrls.forEach(shortUrl => { %> < % }) %>
以上就是关于《node js 生成短链接源码》的全部内容了,感兴趣的话可以点击右侧直接使用哦!》》在线短链接生成器