节点中需要一个函数,该函数将较短的 url 作为输入并返回其实际 url

问题描述 投票:0回答:1

例如作为输入采用此链接,在输出中我需要最终网址https://www.flipkart.com/realme-p1-pro-5g-phoenix-red-128-gb/p/itmc859edf8053dc?pid= MOBGZ8R6Y4FFFHQX¶m=9897&otracker=clp_bannerads_1_8.bannerAdCard.BANNERADS_realme+p1+pro+5g+sale+on_mobile-phones-store_CKXPDU00VGFX&affid=admingopai&affExtParam1=E452B8570 限制是我们不能使用 pupeeter cherio 类型的类似库。我们可以使用 axios 或 http 请求,我需要一个可以快速给我实际 url 的函数。当我尝试时,我被卡住了,因为它有 js 重定向,并且它获得 statuscode200 然后它无法进一步搜索,它将其视为实际的 url

node.js
1个回答
0
投票
const axios = require('axios');

async function resolveShortURL(shortURL) {
let finalURL = shortURL;
let redirects = 0;

try {
    while (redirects < 10) {
        const response = await axios.head(finalURL, { maxRedirects: 0 });
        if (response.headers && response.headers.location) {
            finalURL = response.headers.location;
            redirects++;
        } else {
            break;
        }
    }
} catch (error) {
    console.error("Error resolving URL:", error);
}

return finalURL;
}



const shortURL = "URL;  
resolveShortURL(shortURL)
    .then(finalURL => {
        console.log("Final URL:", finalURL);
    })
    .catch(error => {
        console.error("Error:", error);
    });
© www.soinside.com 2019 - 2024. All rights reserved.