URL Shortener - getting final test to pass

Tell us what’s happening:
Hello! I’ve been working on the URL Shortener challenge and I am stumped on how to pass the last test -

If you pass an invalid URL that doesn’t follow the valid http://www.example.com format, the JSON response will contain { error: 'invalid url' }

Let me know if there is an issue with how I am formatting the JSON response or if the dns.lookup callback function is missing something. I’m stumped here!

Your code so far

app.post('/api/shorturl/new', (req, res, next) => {
  const originalURL = req.body.url;
  const urlObject = new URL(originalURL);
  dns.lookup(urlObject.hostname, (err, address, family) => {
    if (err) {
      res.json({ error: 'invalid url' });
    } else {
      let shortenedURL = Math.floor(Math.random()*100000).toString();
      // create an object(document) and save it on the DB
      let data = new Url({
        url: originalURL,
        shortuUrl: shortenedURL
      data.save((err, data) => {
        if (err) {
        original_url: originalURL,
        short_url: shortenedURL

Link to project: https://repl.it/@Trinitui/boilerplate-project-urlshortener#server.js
Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.193 Safari/537.36.

Challenge: URL Shortener Microservice

Link to the challenge:

1 Like

This is one of the most frustrating exercises in freecodecamp for me personally and seems like it is for everyone too. Other than the dns lookup you will also have to validate the url with regex. I just finished this(with a long shitty solution but it works!). Happy coding :slight_smile:

1 Like

It is not required to use the dns lookup for this project. It is just a suggestion.

1 Like

Oh yea. I realize that now. You are right. I used it anyway. Learnt something new.

1 Like

One of the biggest mistakes people make trying to use dns.lookup is trying to pass a full url instead of just the hostname.

I used the url module to get the hostname. Is there any other way to do it? I mean is it possible to decrease the number of dependencies.

Thanks for the tip to use regex validation - I’ll try that out!

That worked - here’s the snippet of code I added before my dns.lookup to test -

const httpRegex = /^(http|https)(:\/\/)/;
if (!httpRegex.test(originalURL)) {return res.json({ error: 'invalid url' })}

Try this, but the problem is FCC doesn’n accept dns.lookup() solution. My code work well but cant pass the test

const url = require("url");

const  originalURL = url.parse(req.body.url).hostname;

try to console.log(url.parse(req.body.url)); u will see u have to parse this :slight_smile: