节点js url shortener是循环而不是重定向

时间:2017-01-29 14:01:48

标签: javascript node.js mongodb express

我正在使用mongo连接到mLab在Node JS中编写url shortener服务。

现在,用户可以使用网址向服务发送请求以缩短,并返回缩短的网址。但是,如果用户随后将缩短的URL作为请求发送,则不会发生重定向。相反,服务进入循环。

1)如何从数据库中抓取到底是什么? (知道如何做到这一点有助于解决问题)

2)可能是循环问题的原因是什么?

var express = require('express')
var app = express()
var path = require('path');
var port = process.env.PORT || 8080;
var crypto = require("crypto");
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({ // this schema is used for writing to the db
   url : String,  
   key : String   
 });

var urlcntrctr = new Schema( // this schema is used for reading from the db
  { key: String, url : String, _id: String },
  { collection: 'urlcntrctr'}
  );

const SchemaName  = mongoose.model('SchemaName', urlcntrctr); // for reading from the db

app.get('/', (req, res, next) => res.sendFile(path.join(__dirname, '/index.html')) ) ;

app.set('port', (process.env.PORT || 5000));

app.get('/new/:url(*)', function(req, res) {
 var shortenme = req.params[0];
 var showme = req.params[0];
 console.log("User's request: " +shortenme);
 var amItrue = validateURL(shortenme);   
 if (amItrue){   
  connectmongoviamongoose(); 
  var shortenmeObj = yncryptyyn(shortenme); 
  shortenme = shortenmeObj.key; 
  writeToDb(shortenmeObj); b 
  closetheconnection();
  var contractedurl = 'http://firstappever-olddognewtrix123.c9users.io/' + shortenme;
  var responseObject = ({"Original url: ": showme, "Contracted url: ": shortenme });
  res.send(responseObject);
}  
else{console.log("You need to enter a url, beginning with 'http' or 'https' and ending in '.com' or '.org' or whatever!");};   

 })

app.get('/:tag(*)', function(req, res) {
 var targetnumber = req.params.tag; 
 sendforRedirect(req, res);
 sendforRedirect(req, res);
  }) 

function sendforRedirect(req, res){  
   var target = req.params.tag;
  console.log("The value of target is " + target)
 ;       var options = { server: { socketOptions: { keepAlive: 1, connectTimeoutMS: 30000 } }, 
        replset: { socketOptions: { keepAlive: 1, connectTimeoutMS : 30000 }  }   };       

 var mongodbUri = 'mongodb://<dbusername>:<dbuserpassword>@ds159988.mlab.com:59988/urlcntrctr'; 
     mongoose.connect(mongodbUri, options);
     mongoose.Promise = global.Promise;
    var conn = mongoose.connection;             
     conn.on('error', console.error.bind(console, 'connection error:'));  
     conn.once('open', function() {


       console.log("OK, you are connected for the redirect. ") 
       var query = {
        key: {
            $eq: target
         }
       }


     SchemaName.find(query, function (err, doc) {
     if(err){
        console.log(err);
        conn.close();
     };
      if(doc){
        res.redirect(doc.url); // rather than redirecting, it is looping *****************
        conn.close();

      } else {
        res.send("Sorry, we don't recognize that url");

        conn.close();
      }
     }); 
    }); 
 }


 function writeToDb(dataObject){
  mongoose.model('Document', UserSchema);
   var urlFromUser = mongoose.model('Document');
  var urlfromuser = new urlFromUser();
  urlfromuser.url = dataObject.url;
   urlfromuser.key = dataObject.key;
   urlfromuser.save();
 };


 function validateURL(textval) { //copied from   http://stackoverflow.com/questions/1303872/trying-to-validate-url-using-javascript
    var urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/;
   return urlregex.test(textval);
 }



function connectmongoviamongoose(){  
   var mongoose = require('mongoose');
   var options = { server: { socketOptions: { keepAlive: 300000, connectTimeoutMS: 30000 } }, 
       replset: { socketOptions: { keepAlive: 300000, connectTimeoutMS : 30000 } } };       
   var mongodbUri =  'mongodb://<dbusername>:<dbuserpassword>@ds159988.mlab.com:59988/urlcntrctr';
    mongoose.createConnection(mongodbUri, options);
   var conn = mongoose.connection;             
    conn.on('error', console.error.bind(console, 'connection error:'));  
    conn.once('open', function() {
    console.log("OK, you are connected. ") 
    }); 
}

function closetheconnection(){
  var mongoose = require('mongoose');
  mongoose.connection.close();
}

function yncryptyyn(incryptme){
 var ulimit = 6;
  var key = crypto.createHash('md5').update(incryptme).digest("base64");
  key = key.slice(0,ulimit);
  var obj = {
            url: incryptme,
            key: key
        };
        return obj;
}

app.listen(app.get('port'), function() {  
 console.log('Node app is running on port', app.get('port'));
});

2 个答案:

答案 0 :(得分:0)

对于问题1:只需输入console.log,例如:

if(doc){
    console.log(doc);
    res.redirect(doc.url); 
....

更好的是将url查找的全部功能放入自己的函数中,这样就可以独立检查查找的工作和重定向的工作。

答案 1 :(得分:0)

优于console.log语句,您可以使用包node-inspector通过chrome devtools在代码中实际设置breakpoints,并逐步执行代码。

我会注意到,我不清楚你正在缩短什么样的网址(在你的网站内部或外部),但目前看起来你正在调用重定向功能两次,这应该会导致错误本身,第二,如果你重定向到内部网址,你的路线可能会匹配很多你不想要的路线。

最后,你的代码现在是一种混乱,无论你做什么,都会使调试变得更难。尝试根据它们的作用将其分解为不同的文件,并尽可能独立地测试位。