I was writing an API code where the objective was to take in an input URL as a form URL encoded, body parse it, validate it, make a short URL, and when the client requests the short URL, it redirects to the actual URL.
I made the short URL based on the index value of the array to which I was pushing the validated URLs.
For example, if the input body request is ‘www.google.com’ on route ‘/api/shorturl’, it passes the validation and is pushed into an array shorturls = [www.google.com]
. Now when the user requests '/api/shorturl/1'
, the page is redirected to www.google.com . I added a (+1) to index to match the value.
The code works on the body parsing, validation part, the array pushing, and it even redirects to the requested short URL based on the requested URL parameter, to an extent.
The issue is on the URL parameter. When the parameter is ‘2’ or ‘3’ or any other string, I convert it a number and fetch the value from the array. But when the parameter is ‘1’, i.e, /api/shorturl/1 , it doesn’t work, and shows ‘undefined’.
When I logged, the issue was on req.params.url showing undefined.
Why does this work this way? I have attached an image of all console logs.
CONSOLE LOGS
app.post('/api/shorturl', async(req,res)=>{
const url = req.body.url;
try {
const result = await dnsCheck(url);
console.log("ShortUrls",shorturls)
res.json(result);
} catch (error) {
res.json(error);
}
})
//Redirecting to PAGE BY SHORTURL PARAMETER
app.get('/api/shorturl/:url', (req,res) => {
console.log(req.params.url)
let urlIndex = Number(req.params.url) - 1;
console.log(urlIndex)
console.log("Requested",shorturls[urlIndex])
res.redirect(`https://${shorturls[urlIndex]}`)
})
When the parameter is ‘2’ or ‘3’ or any other string, I convert it a number and fetch the value from the array. But When the requested route is /api/shorturl/1, I expect console.log(req.params.url)
to show string 1, so that console.log(urlIndex)
can show number 0, and therefore I can redirect
Shuaib Ahamed is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.