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: boilerplate-project-urlshortener - Replit
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: