The idea is very simple:
1. httpserver obtains the url to be restored;
2. Use httpclient to recursively request this url until http status not in (302,301) is found.
3. Return the restored original url.
The Code is as follows:
Copy codeThe Code is 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 the 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/123'
};
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) {// supports jsonp cross-origin requests
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 a browser and access it directly:
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