URL Shortener microservice need help

when i test the code in freecodecamp it gives me the
When you visit /api/shorturl/<short_url> , you will be redirected to the original URL
here is my code I don’t know what’s wrong it works just fine

app.post('/api/shorturl', function (req, res) {
  const urlRegex = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
  const url = req.body.url;
  if (url.match(urlRegex)) {
    num++;
    finalData.push({short_url: num, original_url: url});
    res.json({ original_url: url, short_url: num});
  } else {
    res.json({ error: 'invalid URL' });
  }
});
app.get('/api/shorturl/:short_url', (req, res) => {
  const short = req.params.short_url;
  for (let i = 0; i < finalData.length; i++) {
        console.log(finalData[i].short_url, short);
    if (finalData[i].short_url === short) {
      res.redirect(finalData[i].original_url);
    } else {
      res.json({ error: 'invalid URL' });
    }
  }
});

Your project link(s)

solution: https://replit.com/@abd-el-rahmane7/boilerplate-project-urlshortener

Your browser information:

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

Challenge: URL Shortener Microservice

Link to the challenge:

You are storing the urls in the server memory? I think you need to persist it in a DB.

i just want to try make it in the server memory instead of DB , it passed all the test actually except that one

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

I’ve tried posting a couple of URLs and it returns “invalid URL” each time even though adding the url worked.

Maybe short is not === because in one case it’s a number and in the url a String ? Have you tried using == or short = parseInt(req.params.short_url) ?

yes i just edited it with parseInt to be a number

i figure out the solution was by doing that

app.get('/api/shorturl/:short_url', (req, res) => {
  const short = parseInt(req.params.short_url);
  const url = finalData.find(data => data.short_url === short);
  if (url) {
    res.redirect(url.original_url);
  } else {
    res.json({ error: 'invalid URL' });
  }
});

which will make the redirect work just fine
thank you all :smiling_face_with_three_hearts:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.