在 Javascript 中展开 Twitter 链接

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

希望使用简单的 Javascript 而不是任何 React/ Node.js 库来扩展 https://t.co 链接。

javascript async-await twitter promise fetch-api
1个回答
0
投票

使用简单的 Javascript 进行三种不同的编程风格,以从 Twitter 短链接获取扩展链接:

//Regex to find expanded URL in the fetch API response
function findFirstUrl(text) {
  const urlRegex = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/g;
  const match = text.match(urlRegex);
  return match ? match[0] : null; // Return the first URL or null if none found
}

//First Way - fetch and then
function expandUrl(shortUrl) {
    return fetch(shortUrl, { method: 'GET' })
        .then(response => {
            return response.text().then((data) => {
                return data;
            }).catch((err) => {
                console.log(err);
            })             
        })
}
expandUrl('https://twitter.com').then((data) => {
    console.log(findFirstUrl(data));
});

//Second Way - fetch and async/ await
async function expandUrl(shortUrl) {
    const response = await fetch(shortUrl);
    const data = await response.text();
    console.log(findFirstUrl(data));
}
expandUrl('https://twitter.com');

//Third Way - fetch and promises
const shortUrls = ['https://twitter.com'];
const expandedUrls = [];
const fetchPromises = shortUrls.map(url => {
    return fetch(url)
        .then(response => response.text())
        .then(data => {
            expandedUrls.push(findFirstUrl(data));
        })
        .catch(error => console.error('Error:', error));
});

Promise.all(fetchPromises)
    .then(() => console.log(expandedUrls))
    .catch(error => console.error('Error:', error));
© www.soinside.com 2019 - 2024. All rights reserved.