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’.
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');
})
)
});