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 + '")'; // 包成 JSONP 回應
}
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);
if (info.protocol != 'http:') { // 此版本不處理 https
_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 request = client.request('GET', path, {
host: info.hostname,
'User-Agent': 'NodejsSpider/1.0'
});
request.end();
request.on('response', function (response) {
if (response.statusCode == 302 || response.statusCode == 301) {
expand(response.headers.location, res); // 遞迴跟隨跳轉
} else {
_write(short_url, res);
}
});
}
// 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) { res.jsonp_cb = params.query.cb; } // 支援 JSONP
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);
});
$ node urlexpand.js
接著在瀏覽器訪問:
https://127.0.0.1:1235/api?u=https://is.gd/imWyT
加上 &cb=foo 則會以 JSONP 形式回應,方便跨域呼叫。
這段範例寫於 Node.js 早期,有幾處已不適用於現代版本,實作時應調整:
http.get() 或 http.request(),並以回呼風格或 Promise 包裝。cb("...") 而不處理引號與換行,等於製造 XSS 缺口。