NodeJS Express response redirect

Tell us what’s happening:
Hi all,

I’m trying to complete the Nodejs URL Shortener Microservice challenge and I bumped into an issue that truly puzzles me.

My current goal is to provide the shortened url in the web address, ask node to check if mongodb has an entry with such url and if yes, redirect the user to the external website hiding behind the shortened url

When I try to get the /api/shorturl/<short_url>, the redirect kinda works as it is able to find the original url. However, it keeps on sending the user to '/api/shorturl/<original_url> rather than <original_url>.

Your code so far

app.get('/api/shorturl/:id', async (req,res)=>{
  try {
    console.log("req.params.id: " + req.params.id)
    const link = await Link.findOne({short_url: req.params.id})
    console.log(link)
    if (link === null) return res.status(404).json({"error":"invalid url"})

    const redir = link.original_url;
    console.log(redir)
    return res.status(301).redirect(redir)

  } catch (err) {
    console.log(err)
    return res.status(500).json('Server error')
  }

I’m have no idea what am I doing wrong.

Here is the link to the project:
Link Changed By Mod

If anyone decides to have a look at the entire code - I’m aware that my app.post function to create new shortened urls is trash and needs re-writing. At least it works, unlike the get request.

Thanks for spending your time to have a look.

Your browser information:

User Agent is: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0

Challenge: URL Shortener Microservice

Link to the challenge:

Hello there,

I think the first thing to fix is the use of dns.lookup. Currently, you are passing the incorrect first argument to it (pay close attention to the docs).

Otherwise, I am not sure how you are testing your application, if it is not saving the correct URLs.

I suggest you look at the docs for res.redirect as well: Express 4.x - API Reference

Hope this helps

Hi,

Thanks for our help. I decided to rewrite my project so it doesn’t strip the provided url of its protocol and does not use dns.lookup. After all, the url needs to be of valid format, doesn’t need to actually exist.

Thanks

1 Like

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