short是一个开源的短域名服务,使用 Node.js 与 MongoDB 搭建,可以直接在你的Server程序中调用,也可以通过Node.js的httpserver模块以一个服务启动。
可以直接通过Node.js的 npm 进行安装:
$npminstallshort可以直接在你的Node.js项目中这样调用,生成长域名对应的短链接:
varmongoose=require("mongoose");varshort=require("short");mongoose.connect("mongodb://localhost/short");varURL="https://nodejs.org/";short.make(URL,function(error,shortURL){if(error){console.error(error);}else{short.get(shortURL.hash,function(error,shortURLObject){if(error){console.error(error);}else{varURL=shortURLObject[0].URLvarhash=shortURLObject[0].hash;console.log(URL,hash);process.exit(1);};});}});下面代码用于搭建一个提供短域名跳转的HTTP服务:
varhttp=require("http");varmongoose=require("mongoose");varshort=require("short");mongoose.connect("mongodb://localhost/short");varapp=http.createServer(function(request,response){varhash=request.url.slice(1);if(request.url==="/"){response.writeHead(200,{"Content-Type":"text/html"});response.write("URLnotfound!");response.end();}else{short.get(hash,function(error,shortURLObject){if(error){console.error(error);}else{if(shortURLObject){varURL=shortURLObject[0].URL;response.writeHead(302,{"Location":URL});response.end();}else{response.writeHead(200,{"Content-Type":"text/html"});response.write("URLnotfound!");response.end();}};});}});app.listen(8080);console.log(">Openhttps://localhost:8080/kQ4c");
评论