如何从Rapid API获取数据?歌曲列表请求forEach报错求助
Hey, let's break down why you're hitting this error and fix it up quickly!
First off, that TypeError is popping up because you're trying to run forEach on something that's undefined. There are two small issues in your code causing this:
1. You're not returning the parsed JSON from your first .then handler
In your current code, the first .then has:
.then(response => { response.json(); })
The function here doesn't return anything, so the next .then receives undefined instead of the parsed JSON data. You need to return the result of response.json()—either explicitly with a return statement, or use an implicit return by dropping the curly braces:
.then(response => response.json())
2. The Deezer API returns songs nested in a data property
If you check the structure of the response from this RapidAPI endpoint, the actual array of songs isn't the top-level object—it's nested under the data key. So instead of trying to run forEach on parsedJson directly, you need to target parsedJson.data.
Here's your fixed full code:
function loadData() { fetch("https://deezerdevs-deezer.p.rapidapi.com/search?q=eminem", { "method": "GET", "headers": { "x-rapidapi-host": "deezerdevs-deezer.p.rapidapi.com", "x-rapidapi-key": "45ea72d0cbmsh5a68a7ddaa76fefp17c953jsn0a280e030350" } }) .then(response => response.json()) // Fixed: implicit return of parsed JSON .then( parsedJson => { const list = document.querySelector('.list'); // Fixed: iterate over parsedJson.data instead of parsedJson parsedJson.data.forEach(element => { const listElem = document.createElement('li') const textNode = document.createTextNode(element.title) listElem.appendChild(textNode) list.appendChild(listElem) }); }) .catch(err => { console.log(err); }); }
A quick pro tip: Next time you're working with a new API, add a console.log(parsedJson) in the .then handler before processing the data. This lets you inspect the exact structure of the response and avoid guessing where the data you need lives!
内容的提问来源于stack exchange,提问作者Xena

