Reputation:
I'm trying to make a function that redirects you to another website, but instead of redirecting to another website its assuming that the weblink that i want to redirect to is a route in my website.
app.get('/:shorturl', (req, res) => {
UrlShort.findOne({'ShortUrl': req.param('shorturl')}, (err, doc) => {
if(err) return res.send('Error Reading Database!');
var re = new RegExp("$(http|https)://", "i");
if(re.test(doc.OriginalUrl)){
res.redirect(301, doc.OriginalUrl);
} else {
res.redirect(301, 'http://' + doc.OriginalUrl);
}
});
});
Instead of redirecting to the other web site it redirects to this:
http://localhost:3000/www.google.com
Upvotes: 0
Views: 793
Reputation: 319
Your problem is not redirect function. It seems true. But your Regex is wrong. You need to change your regex to
^(http|https)://
Here is working code example that I've tested:
app.get("/redirect", function(req, res) {
var url = "http://www.google.com";
var re = new RegExp("^(http|https)://", "i");
if(re.test(url)){
console.log("#LOG1", url);
res.redirect(301, url);
} else {
console.log("#LOG2", 'http://' + url);
res.redirect(301, 'http://' + url);
}});
Upvotes: 2