URL shortener microservice: it works but the test doesn't accept it

Tell us what’s happening:
I was doing the url shortener microservice project and I’ve made a simple app that although it’s a bit messy it seems to work perfectly fine and I don’t know seriously where I am wrong

This was the code I’ve come up with:

const url = new mongoose.Schema({
  url: String
})
const URL = mongoose.model("URL", url)
let links = []
app.post("/api/shorturl/", (req,res) => {
  const bodyurl = req.body.url
  if(!bodyurl.match(/^http/i)) {
    res.json({ error : "invalid url"})
   }
 let newUrl = new URL({url: bodyurl})
  links.push(newUrl)

  res.json({original_url: newUrl.url, short_url:newUrl._id})
})

app.get("/api/shorturl/:id", (req,res) => {
   const id = req.params.id 
   console.log(id)
   console.log(links)
   for(let i = 0; i<links.length; i++) {
     if(links[i]._id.toString() !== id.toString()) {
       res.json({error: "invalid url"})
     }
     else {
       res.redirect(links[i].url)
     }
   }
   
   
})

The only thing that doesn’t pass the test is :

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

Your project link(s)
solution: https://replit.com/@lucal2/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/91.0.4472.114 Safari/537.36

Challenge: URL Shortener Microservice

Link to the challenge:

Look at the output of this and make sure you have some links actually getting logged when you run the fCC tests against your project. You’ve got mongoose setup partially, but links is a globally declared array and you are trying to store links there instead of with mongoose. You need to store the URL data with mongoose and fetch it back again on this route.

I’m not certain, but I think in express you are not really guaranteed to have access to any variable between server requests/responses. Regardless, it’s not a viable solution for storing data (your data gets erased every restart), so you need to finish hooking up your MongoDB data storage.

1 Like

Thanks!!! Now it works fine

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