Redirecting to a new Url with Express

Redirecting to a new Url with Express
0

#1

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?


#2

Hi @critesjosh

I think the problem is that you’re stringifying the url, so when you send it to redirect, it’s seeing that as a relative path of your current domain. Try removing the stringify function and redirecting the raw value.


#3

That was it Joe. Thanks!

Staring at the screen for too long really reduces my debugging skills.


#4

No problem dude.

I definitely no that problem! Then it’s always usually the simplest thing to fix :grin: