You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Node.js中提取URL信息并展开$ref链接获取API数据

Got it, let's break down how to solve this in Node.js! You've got an API response with $ref links pointing to additional league data, and you need to fetch those links and pull out the info you need. Here's a straightforward, practical approach:

Step 1: Choose an HTTP client

First, you'll need a way to make HTTP requests. You can use Node.js's built-in fetch (available in Node 18+) or a popular library like axios. If you go with axios, install it first:

npm install axios

Here's a complete example using axios (we'll use Promise.all to fetch all links in parallel for efficiency):

const axios = require('axios');

async function fetchAndExpandRefs() {
  try {
    // First, grab the initial response containing the $ref links
    const initialResponse = await axios.get('YOUR_INITIAL_API_ENDPOINT'); // Replace with your actual API URL
    const items = initialResponse.data.items;

    // Create a list of promises to fetch each $ref URL
    const leagueFetchPromises = items.map(item => {
      const refUrl = item['$ref'];
      return axios.get(refUrl);
    });

    // Wait for all fetch requests to finish
    const leagueResponses = await Promise.all(leagueFetchPromises);

    // Extract the specific data you need from each league response
    const extractedLeagueData = leagueResponses.map(response => {
      const league = response.data;
      // Customize this based on the actual fields returned by the ESPN API
      return {
        leagueId: league.id,
        leagueName: league.name,
        abbreviation: league.abbreviation,
        sportType: league.sport.name
      };
    });

    console.log('Final extracted league data:', extractedLeagueData);
    return extractedLeagueData;
  } catch (error) {
    console.error('Something went wrong:', error.message);
    throw error;
  }
}

// Run the function
fetchAndExpandRefs();

If you prefer native fetch (Node 18+):

async function fetchAndExpandRefsWithNativeFetch() {
  try {
    const initialResponse = await fetch('YOUR_INITIAL_API_ENDPOINT');
    const initialData = await initialResponse.json();
    const items = initialData.items;

    const leagueFetchPromises = items.map(async item => {
      const refResponse = await fetch(item['$ref']);
      return refResponse.json();
    });

    const leagueData = await Promise.all(leagueFetchPromises);

    const extractedLeagueData = leagueData.map(league => ({
      leagueId: league.id,
      leagueName: league.name,
      abbreviation: league.abbreviation,
      sportType: league.sport.name
    }));

    console.log('Final extracted league data:', extractedLeagueData);
    return extractedLeagueData;
  } catch (error) {
    console.error('Error processing data:', error.message);
    throw error;
  }
}

fetchAndExpandRefsWithNativeFetch();

Quick tips:

  • Replace YOUR_INITIAL_API_ENDPOINT with the actual URL that returns the items array with $ref links.
  • Adjust the extractedLeagueData mapping to match the real structure of the ESPN league API responses (I guessed common fields, but you'll need to tweak this based on what the API actually sends back).
  • The try/catch blocks help catch network errors or missing data fields, so you can debug issues easily.

内容的提问来源于stack exchange,提问作者rasilvap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:24:02