URL shortener - it seems to work but doesn't pass

app.post('/api/shorturl/new', function(req, res) {
  const url = req.body.url;
  console.log(url);

  const protocol = /^https?:\/\//i;
  const dnsUrl = url.replace(protocol, '');

  dns.lookup(dnsUrl, async function(err, exists) {
    if (exists) {
      console.log('valid url: ' + dnsUrl);
      try {
        let findOne = await URL.findOne({
          original_url: url
        });
        if (findOne) {
          res.json({
            original_url: findOne.original_url,
            short_url: findOne.short_url
          });
        } else {
          const urlCode = shortId.generate();
          console.log(urlCode);
          findOne = new URL({
            original_url: url,
            short_url: urlCode
          });
          await findOne.save();
          res.json({
            original_url: findOne.original_url,
            short_url: findOne.short_url
          });
        }
      } catch (err) {
        console.log(err);
        res.status(500).json('Server error...')
      }
    } else {
      console.log('error: invalid url');
      res.json({ error: 'invalid url' });
    }
  });
});

app.get('/api/shorturl/:short_url?', function(req, res) {
  URL.findOne({short_url: req.params.short_url})
  .then(result => {
    if(result) {
      console.log(`Successfully found document: ${result}.`);
      const orig = result.original_url;
      const re = new RegExp("^(http|https)://", "i");
      if (re.test(orig)) {
        console.log("#LOG1", orig);
        res.redirect(301, orig);
      } else {
        console.log("#LOG2", 'http://' + orig);
        res.redirect(301, 'http://' + orig);
      }
    } else {
      console.log("No document matches the provided query.");
      return;
    }
  })
  .catch(err => console.error(`Failed to find document: ${err}`));
});

link to repl -> https://boilerplate-project-urlshortener.kendalwon.repl.co/

1 Like

Hi and welcome to the forum!

Please provide more information, such as how your code is not workingas you expect and which tests are failing so that it is easier for others to help you.


I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thanks for the reply and for the formatting assistance. It does not pass two of the tests, but everything works for me.

These are the tests that are not passing:

You can POST a URL to /api/shorturl/new and get a JSON response with original_url and short_url properties. Here’s an example: { original_url : 'https://freeCodeCamp.org', short_url : 1}

When you visit /api/shorturl/<short_url> , you will be redirected to the original URL.

I’m having the same issue with this project. The API seems to be working fine based on my own testing, but it doesn’t pass those two tests. Here’s my app and a snapshot of the basic logger output after the tests . Please let me know if any additional information is necessary.

Hello!

The problem is that your tests don’t work on other valid URLs:

It’s not enough to just remove the protocol from the URL being shortened.

For a more robust solution, take a look at the URL module on nodejs: https://nodejs.org/docs/latest-v12.x/api/url.html#url_the_whatwg_url_api

1 Like

You have the same problem. The method you’re using to retrieve the host part of the URL falls short.

Your URL Shortener should work with the following, but not limited to, URLs:

1 Like

Thank you so much for your response; I’d been scratching my head about this since yesterday and ended up learning a lot about URL structure. :slight_smile:

1 Like

Thanks so much for the help! I was able to make the changes and pass. Thanks again.

1 Like

A post was split to a new topic: URL Shortener Question