Node.js 短链接服务
短链接是将长 URL 转为短码,访问短链时通过重定向跳回原网址。用于短信、社交媒体等字符受限场景,也可统计点击量。
原理
长URL → 生成唯一短码 → 存入数据库
访问 /短码 → 查数据库 → 302 重定向 → 原始长URL数据库表设计
sql
CREATE TABLE `short` (
`id` INT NOT NULL AUTO_INCREMENT,
`short_id` VARCHAR(255) NOT NULL COMMENT '短码',
`url` VARCHAR(255) NOT NULL COMMENT '网址',
PRIMARY KEY (`id`)
);完整代码
bash
npm install express knex mysql2 shortidjs
import knex from 'knex'
import express from 'express'
import shortid from 'shortid'
const app = express()
app.use(express.json())
const db = knex({
client: 'mysql2',
connection: { host: 'localhost', user: 'root', password: '123456', database: 'short_link' }
})
// 生成短链接
app.post('/create_url', async (req, res) => {
const { url } = req.body
const short_id = shortid.generate()
await db('short').insert({ short_id, url })
res.send(`http://localhost:3000/${short_id}`)
})
// 重定向
app.get('/:shortUrl', async (req, res) => {
const result = await db('short').select('url').where('short_id', req.params.shortUrl)
if (result?.[0]) {
res.redirect(result[0].url) // 302 重定向到原始 URL
} else {
res.send('Url not found')
}
})
app.listen(3000)流程
POST /create_url { url: "https://xxx.com/very-long-url" }
→ shortid.generate() → "abc123"
→ 返回 http://localhost:3000/abc123
GET /abc123
→ 查库 → url = "https://xxx.com/very-long-url"
→ res.redirect() → 浏览器跳转