URL Shortener Service - Test not passing

Hey there! I’m stuck at this challenge. The app works like it suppose I think, but im not passing the tests.

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const app = express();
const bodyParser = require("body-parser")
const mongoose = require('mongoose')
const { Schema } = mongoose
const dns = require("dns")

// Basic Configuration
const port = process.env.PORT || 3000;

mongoose.connect(process.env.MONGO_URI, (e) => { console.log("hola Mongo") })

app.use(bodyParser.urlencoded())
app.use(cors());

app.use('/public', express.static(`${process.cwd()}/public`));

app.get('/', function(req, res) {
  res.sendFile(process.cwd() + '/views/index.html');
});


const urlSchema = new Schema({
  original_url: String,
  short_url: String
})
const urlModel = mongoose.model("URL", urlSchema)


// Your first API endpoint
app.post('/api/shorturl', function(req, res) {
  let url = req.body.url
  if (!/(https?:\/\/)/.test(url)) return res.send({ error: "invalid url" })
  let urlDns = url.replace(url.match(/(https?:\/\/)/)[0], "")
  dns.lookup(urlDns, async (e) => {
    if (!e) {
      const numUrl = await urlModel.estimatedDocumentCount();
      let urlDoc = new urlModel({
        original_url: url,
        short_url: numUrl + 1
      })
      urlDoc.save()
      res.json({ original_url: urlDoc.original_url, short_url: Number(urlDoc.short_url) });
    }else{
      res.status(404).send({error:"invalid HostName"})
    }
  })
})
app.get("/api/shorturl/:id",async (req,res)=>{
  let id=req.params.id
  let url=await urlModel.findOne({short_url:id})
  
  res.redirect(url.original_url)
})
app.get("/api",async(req,res)=>{
  const urls=await urlModel.find({})
  res.json(urls)
})

app.get("/api/delete", async (req, res) => {
  await urlModel.deleteMany({})
  res.send("La base de datos ha sido eliminada")
})


app.listen(port, function() {
  console.log(`Listening on port ${port}`);
});

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36

Challenge: URL Shortener Microservice

Link to the challenge:

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 (’).

dns.lookup takes just the hostname, you did not remove the end path.

https://nodejs.org/api/dns.html#dnslookuphostname-options-callback

Log out urlDns and compare it to for example new URL(url).hostname

console.log(urlDns)
console.log(new URL(url).hostname)
1 Like

Hi! Thanks for reply.

I did what you mentioned.

let urlDns = url.replace(url.match(/(https?:\/\/)/)[0], "")
return res.json({urlDns,url:new URL(url).hostname})

Notice that I first I replace the “http://” part from the url.
The result is this.

{"urlDns":"freeCodeCamp.org","url":"freecodecamp.org"}

There is only case differences.

Did you do this?

let urlDns = url.replace(url.match(/(https?:\/\/)/)[0], "");
console.log(urlDns);
console.log(new URL(url).hostname);

Compare the two console.log outputs when you submit the project.

If you pass new URL(url).hostname to dns.lookup you will pass the tests.

1 Like

Thanks! That was it. I didn’t think that it will make such a difference.

1 Like

You are not the first to have issues with dns.lookup. It is strict about what it accepts as the host argument.

I’m guessing if they wanted to they could do some escaping for the argument (like trailing paths, etc.). But that would likely complicate the code maintenance unnecessarily.

Either way the dns.lookup function it was accepting my urlDns version. Because otherwise the backend it will respond with an error of invalid HostName.

I think the problem was in the test. It seems that some validation is case sentitive.

If you check the network tab when submitting (with your initial code) you would see that is exactly what the response is.

Response with your initial code.

initial-code-response