short是一个开源的短域名服务,使用 Node.js 与 MogoDB 搭建,可以直接在你的Server程序中调用,也可以通过Node.js的httpserver模块以一个服务启动。
可以直接通过Node.js的 pm 进行安装:
$pmistallshort可以直接在你的Node.js项目中这样调用,生成长域名对应的短链接:
varmogoose=require("mogoose");varshort=require("short");mogoose.coect("mogodb://localhost/short");varURL="https://odejs.org/";short.make(URL,fuctio(error,shortURL){if(error){cosole.error(error);}else{short.get(shortURL.hash,fuctio(error,shortURLObject){if(error){cosole.error(error);}else{varURL=shortURLObject[0].URLvarhash=shortURLObject[0].hash;cosole.log(URL,hash);process.exit(1);};});}});下面代码用于搭建一个提供短域名跳转的HTTP服务:
varhttp=require("http");varmogoose=require("mogoose");varshort=require("short");mogoose.coect("mogodb://localhost/short");varapp=http.createServer(fuctio(request,respose){varhash=request.url.slice(1);if(request.url==="/"){respose.writeHead(200,{"Cotet-Type":"text/html"});respose.write("URLotfoud!");respose.ed();}else{short.get(hash,fuctio(error,shortURLObject){if(error){cosole.error(error);}else{if(shortURLObject){varURL=shortURLObject[0].URL;respose.writeHead(302,{"Locatio":URL});respose.ed();}else{respose.writeHead(200,{"Cotet-Type":"text/html"});respose.write("URLotfoud!");respose.ed();}};});}});app.liste(8080);cosole.log(">Opehttps://localhost:8080/kQ4c");
评论