Monday, 5 June 2017

Node not redirecting to external url in React app

So I'm building a React, Node, and Express url-shortener app. When a user requests a shortened link the request is not redirected to the correct long url but instead, it's redirected back to my root page with the long url appended to it. So a short url localhost:8080/ejd79xd with original url www.google.com is getting redirecting to localhost:8080/www.google.com

Here are my request handlers:

app.get('/:shortLink', shortLinkRouter)
app.get('/', (req, res) => res.sendFile(path.join(__dirname, '../public/index.html')))

and the shortLinkRouter:

const shortLinkRouter = (req, res) => {
  let path = req.params.shortLink
  let redirectUrl
  console.log('shortlink is ', path)          // debugging
  Link.selectByShortLink({ shortLink: path }) // 'get original url from DB'
  .then(link => {
    if (!link) {
      console.log('err selecting link by url ', link) // debugging
      throw new Error(`Link with short path '${path}' does not exist`)
    } else {
      redirectUrl = link.url
      return Link.incrementVisit({ shortLink: path }) // increment visit count inDB
    }
  })
  .then(() => {
    console.log('redirect url is: ', redirectUrl)
    res.redirect(302, redirectUrl)
  })
  .catch((err) => {
    console.log(err)
    res.send('<h2>404: Not Found</h2>')
  })
}

The page renders the 404: Not Found with the original url appended to my url. Here is the stack trace:

shortlink is  d8b99f6
redirect url is:  www.google.com
shortlink is  www.google.com
err selecting link by url  null
Error: Link with short path 'www.google.com' does not exist
    at Link.selectByShortLink.then.link (/Users/keithalpichi/Developer/lil-link/server/routes/index.js:19:13)

From the stack I assume:

  • the original request works. The first two console.logs work.
  • the third log shortlink is www.google.com is going back to this request handler
  • the fourth log err selecting link by url null is correct because www.google.com does not exist as a shortened url in my DB
  • As a result of this thrown error the catch prints the error.

From what I know with React and client-side routing the most popular approach for routing is to use a catch-all wildcard route (app.get('*', (req, res) => res.sendFile(/* a static html file */))). I original had these approach but it still wasn't working.

Why is my redirect requesting my servers endpoint again? Why is the shortened url appended to the end and not correctly redirecting? Thank you in advance!



via Keith Alpichi

No comments:

Post a Comment