node.js_url_shortener_w_qr_code_generation_api/service by Matt Grill


/ Published in: JavaScript
Save to your folder(s)

It currently uses redis as a store for the data. The url's are pretty long since it's all base64 encoded data and the images are returned as base64 encoded PNG's but that can be solved pretty easily. This could be used a service for something kind of authentication front end, drupal


Copy this code and paste it in your HTML
  1. var express = require('express'),
  2. app = express(),
  3. redis = require('redis'),
  4. client = redis.createClient(),
  5. QRCode = require('qrcode');
  6.  
  7. app.use(express.bodyParser());
  8.  
  9. app.post('/new', function(req, res){
  10. if(req.body.url){
  11. var url_id = new Buffer(req.body.url).toString('base64');
  12. client.keys(url_id,function(err,keys) {
  13. if (err) res.send({'message':'Internal Server Error'},500);
  14. if (keys.length != 0){
  15. res.send({'message':'Conflict','keys':keys},409);
  16. }
  17. else {
  18. client.set(url_id, req.body.url,function(err,status){
  19. if (err) res.send({'message':'Internal Server Error'},500);
  20. else {
  21.  
  22. QRCode.toDataURL('http://localhost:3000/go/'+url_id,function(err,dataURL){
  23. var response = {
  24. qrcode : dataURL
  25. };
  26. response[url_id] = req.body.url;
  27. res.send(response,200)
  28. });
  29.  
  30. };
  31. });
  32.  
  33. }
  34. });
  35.  
  36. }
  37. else {
  38. res.send(400)
  39. }
  40. });
  41.  
  42. app.get('/go/:hash',function(req,res){
  43. if(req.params.hash){
  44. client.exists(req.params.hash, function (err, doesExist) {
  45. if (doesExist == false) {
  46. res.send({'message':'Not Found'},404);
  47. };
  48. if (doesExist == true) {
  49. client.get(req.params.hash,function(err,url) {
  50. if (err) res.send({'message':'Internal Server Error'},500);
  51. else {
  52. res.redirect(url.toString(), 301);
  53. }
  54. })
  55. }
  56. });
  57. }
  58. else{
  59. res.send(404)
  60. }
  61. });
  62.  
  63. app.listen(3000);
  64. console.log('Listening on port 3000');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.