如何阅读 JSON 并重定向下载

How to read JSON and redirect a download

我正在努力让我的网站读取 githubs api 并自动将用户发送到最新下载 link,在这种情况下,标签是 browser_download_url,我将如何开始使用 JSON.parse() 或其他东西来阅读并重定向用户

如果您使用 fetch API,则无需调用 JSON.stringify

您可以从 JSON 对象解构 URL,然后为该 URL 打开一个新选项卡以启动下载。

fetch('https://api.github.com/repos/portablemc/portablemc/releases/latest')
  .then(response => response.json())
  .then(json => {
    const { assets: [ { browser_download_url } ] } = json; // Destructure
    
    console.log(browser_download_url);                     // Log the URL
    
    window.open(browser_download_url, '_blank');           // Open a new tab
  });

如果你想让它成为一个按钮,你可以这样写一个函数:

const main = async () => {
  const btn = await initDownloadButton('#download-btn', {
    url: 'https://api.github.com/repos/portablemc/portablemc/releases/latest'
  });
  console.log(`Initialized: #${btn.id}`);
};

const initDownloadButton = async (btn, options) => {
  if (typeof btn === 'string') btn = document.querySelector(btn);
  const downloadUrl = await fetchLatestDownloadUrl(options.url);
  btn.addEventListener('click', () => {
    console.log(`Opening: ${downloadUrl}`);
    window.open(downloadUrl, '_blank')
  });
  return btn;
};

const fetchLatestDownloadUrl = async (url) => {
  const response = await fetch(url);
  const { assets: [ { browser_download_url } ] } = await response.json();
  return browser_download_url;
}

main();
<button id="download-btn">Download</button>