https://s.lazada.com.my/s.ny94J
Given the shortened url is as above, when paste it in a browser, it will redirect me with full url where I can extract the product id from it
But in my code, I can't seem to expand it
try {
const response = await axios.get(url, { maxRedirects: 5 });
console.log('Res', response.request.res);
const finalUrl =
response.request.res.responseUrl || response.config.url; // Resolved URL
console.log('Resolved Final URL:', finalUrl);
const match = finalUrl.match(/-i(\d+)-/);
if (match) {
console.log('Product ID extracted from resolved URL:', match[1]);
return match[1];
}
} catch (error) {
console.error(
'Error resolving mobile shortened link:',
error.response?.data || error.message
);
throw error;
}
Where the response.request.res.responseUrl also return https://s.lazada.com.my/s.ny94J
Your code would work if the redirection was caused by a 302 Found response. But this website does it differently: It responds with 200 OK and an HTML page that contains a <meta http-equiv="refresh">
element. This redirects you only after the browser has loaded and parsed the HTML page.
You would have to perform such parsing in your Node.js code. Here is a very rudimentary way to do it:
const response = await axios.get("https://s.lazada.com.my/s.ny94J");
console.log(response.data.match(
/<meta http-equiv="refresh" content=".*?;url=(.*?)"/
)[1]);