Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

res.redirect is not a function – express.js

I am new to Express.js and am trying to create a URL shortener.

When the user naviagtes to domain.com/r/ I query the DB for the param and get the actual URL.

I use res.redirect to try to redirect to their stored URL but it fails with ‘res.redirect is not a function’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please see the snippet below:

router.get('/r/:shortUrl', function(req, res) {

  connectDatabase.then(
    checkDatabase(req.params.shortUrl)
      .then( res => {
        console.log('checkdatdabase res => ' + res); //res = 'https://www.google.com'
        res.redirect(res); //TypeError: res.redirect is not a function
      })
      .catch(e => {
        //executed due to above error
        console.error(e);
        res.redirect(307, '/home');
      })
  )
});

Any advice would be much appreciated as this is a learning project for me.

>Solution :

datdabaseRes and res should be different variable name. Otherwise res has the respose object of database connection in the scope you are trying to use it.

   

router.get('/r/:shortUrl', function(req, res) {
  connectDatabase.then(
    checkDatabase(req.params.shortUrl)
      .then( datdabaseRes => {
        console.log('checkdatdabase res => ' + datdabaseRes); //res = 'https://www.google.com'
        res.redirect(datdabaseRes); //TypeError: res.redirect is not a function
      })
      .catch(e => {
        //executed due to above error
        console.error(e);
        res.redirect(307, '/home');
      })
  )
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading