How do I resolve this error ? "ERR_TOO_MANY_REDIRECTS"

36 Views Asked by At

I am trying to build a URL shortener. When the short URL is pasted in a browser,it should redirect the user to the original long URL but I am seeing the error message "ERR_TOO_MANY_REDIRECTS".

I have also verified that the short URL and long URLs are saved in the database. Before pasting the short URL in the browser. Additionally, I've tested with console.logs and can see that it's going in an infinite loop before it's killed. I've ensured that the route to handle redirection is placed at the very end of my server file. Here's

app.get('/:shortenedUrl', async (req, res) => {
  const {shortenedUrl} = req.params;
  console.log('1');
  try {
    const url = await Url.findOne({ shortenedUrl });
    console.log('2');
    if (url) {
      const redirectToUrl = `http://localhost:5000/${shortenedUrl}`;
      res.redirect(redirectToUrl);
    } else {
      res.status(404).json({ message: 'URL not found' });
    }
    console.log('3');
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Internal server error' });
  }
});  
0

There are 0 best solutions below