Redirecting to a new Url with Express

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?

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.

1 Like

That was it Joe. Thanks!

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

No problem dude.

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

Sorry for bumping this post 3 years later! But since I got here by Googling this issue and I was not using “JSON.stringify”, I want to let others know that in my case I fixed it by appending “https://” to the urls that didn’t have it (ex. www.facebook.com)

If that still doesn’t work, try appending the status like this:

res.status(301).redirect(urlWithProtocol);
1 Like