The idea is very simple:
1. Httpserver get the URL that needs to be restored;
2. Use httpclient recursion to request this URL until you find HTTP status not in (302, 301).
3. Returns the original URL of the restore.
Well, the code is as follows:
Copy Code code as follows:
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: ') {//cannot request 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 Service
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) {//Support JSONP cross domain request
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);
});
Start your Web server:
$ node Urlexpand.js
Open Browser Direct access:
Http://127.0.0.1:1235/api?u=http://is.gd/imWyT
or access my test server:
Http://yongwo.de:1235/api?u=http://is.gd/imWyT&cb=foo