Back End Development and APIs Projects - URL Shortener Microservice

Tell us what’s happening:

Can’t get the last test to work

The relevant chunk of my code:

let addresses = {};

function isValidUrl(string) {
  try {
    new URL(string);
    return true;
  } catch (err) {
    return false;
  }
}

app.get("/api/shorturl/:url", (req, res) => {
  const { url } = req.params;
  res.redirect(addresses[url]);
});

app.post("/api/shorturl", (req, res) => {
  const { url } = req.body;
  if(isValidUrl(url)){
  const short_url = Object.keys(addresses).length + 1; // Generate unique short_url
  addresses[short_url] = url;
  res.json({
    original_url: `${url}`,
    short_url: short_url,
  });}
  else
  res.json({ error: 'invalid url' })
});

Full code in the github repository if needed.

The code itself works:



image

Thank you!

###Your project link(s)

githubLink: GitHub - SeGePop/boilerplate-project-urlshortener: A boilerplate for a freeCodeCamp project.

solution: http://localhost:3000

Your browser information:

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

Challenge Information:

Back End Development and APIs Projects - URL Shortener Microservice

Created a branch to test the recommended dns.lookup() method:

boilerplate-project-urlshortener/index.js at dsn.checkup · SeGePop/boilerplate-project-urlshortener (github.com)

app.post("/api/shorturl", (req, res) => {
  const { url } = req.body;
  dns.lookup(url, (err, addresses) => {
    if (err) {
      res.json({ error: "invalid url" });
    } else {
      const short_url = Object.keys(local_addresses).length + 1; // Generate unique short_url
      local_addresses[short_url] = url;
      res.json({
        original_url: `${url}`,
        short_url: short_url,
      });
    }
  });
});

this method flips my results, and I must be using it wrong because the code does not work.

I was right, using dns.lookup() wrong. It checks the domain, not the full url, so I needed to extrac that first:

function extractDomain(url) {
  try {
    const parsedUrl = new URL(url);
    return parsedUrl.hostname;
  } catch (error) {
    return null;
  }
}

after that,

app.post("/api/shorturl", (req, res) => {
  const { url } = req.body;
  **const domain = extractDomain(url);**
  dns.lookup(**domain**, (err, addresses) => {

Relevant bits between ** **