I am working on url shortener and I am almost done. I am just stuck on the last piece and it is driving me mad. Here is my code that
Here is the code in the route, reading the url and directing flow. The shortened URLs are caught by the first app.route and sent to shorten.sendAway.
module.exports = function (app, db) {
var shorten = new ShortenerHandler(db);
app.route('/([0-9]+)$')
.get(shorten.sendAway);
app.route('/')
.get(function (req, res) {
res.sendFile(process.cwd() + '/public/index.html');
});
app.route('/new/*')
.get(shorten.shortenUrl);
};
Here is shorten.SendAway that handles the shortened urls. I call res.redirect(); but the output is all wrong.
this.sendAway = function (req, res) {
var url = req.url;
url = url.slice(1);
storedUrls.findOne({ "shortened-url": `https://url-shortener34.herokuapp/${url}` }, function(err, result) {
if (err) {
throw err;
}
else if (result) {
var redirectTo = JSON.stringify(result["original-url"]);
res.redirect(redirectTo);
console.log(redirectTo);
} else {
res.send('Please enter a valid shortened url.');
}
});
};
This is what I get as output. Cannot GET /%22https://amazon.com%22. And the string in the address bar reads http://localhost:8080/“https://amazon.com”.
It is appending the url to the end of the current url. How do i resolve this?