Node.js 实现短链接还原为原始URL的示例

作者:终端旅客时间:2026-10-25 17:14:10浏览:617

本文介绍如何使用Node.js编写一个简易的短链接还原服务。通过HTTP客户端递归追踪301和302重定向响应,直至获取最终URL。代码包含JSONP支持,可直接通过浏览器或API调用测试短链接的真实地址。

Node.js 短链接还原服务实现

核心逻辑十分直观:


首先,HTTP服务器接收需要还原的短链接URL;


其次,利用HTTP客户端对该URL发起递归请求,持续追踪直到HTTP状态码不再是302或301为止;


最后,将追踪到的原始URL返回给用户。



具体实现代码如下:


代码如下:

 
var net = require('net'),
http = require('http'),
url = require('url'),
fs = require('fs');
var DEFAULT_PORTS = {
'http:': 80,
'https:': 443
}; 
var INDEX_TPL = fs.readFileSync('index.html');
function _write(str, res, content_type) {
if(res.jsonp_cb) {
str = res.jsonp_cb + '("' + str + '")';
} 
res.writeHead(200, {
'Content-Length': str.length,
'Content-Type': content_type || 'text/plain'
}); 
res.end(str);
}; 
function expand(short_url, res) {
var info = url.parse(short_url);
// console.log('info: ' + JSON.stringify(info));
if(info.protocol != 'http:') { // 无法请求https的url?
_write(short_url, res);
return;
} 
var client = http.createClient(info.port || DEFAULT_PORTS[info.protocol], info.hostname);
var path = info.pathname || '/';
if(info.search) {
path += info.search;
} 
var headers = {
host: info.hostname,
'User-Agent': 'NodejsSpider/1.0'
}; 
var request = client.request('GET', path, headers);
request.end();
request.on('response', function (response) {
if(response.statusCode == 302 || response.statusCode == 301) {
expand(response.headers.location, res);
} else {
_write(short_url, res);
} 
}); 
}; 
//expand('http://sinaurl.cn/hbMUII');
// http服务
http.createServer(function(req, res){
if(req.url.indexOf('/api?') == 0) {
var params = url.parse(req.url, true);
if(params.query && params.query.u) {
if(params.query.cb) { // 支持jsonp跨域请求
res.jsonp_cb = params.query.cb;
} 
expand(params.query.u, res);
} else {
_write('', res);
} 
} else {
_write(INDEX_TPL, res, 'text/html');
} 
}).listen(1235);
process.on('uncaughtException', function (err) {
console.log('Caught exception: ' + err);
}); 

启动你的web服务器吧:


$ node urlexpand.js


打开浏览器直接访问:


http://127.0.0.1:1235/api?u=http://is.gd/imWyT


或者访问我的测试服务器:


http://yongwo.de:1235/api?u=http://is.gd/imWyT&cb=foo

作者最新文章