这个问题可能是由于API请求返回的结果没有按照预期的格式返回,导致无法读取结果而引起的。解决方法有两个:
fetch('url/to/api') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { console.log(data); }) .catch(error => { console.error('There was an error:', error); });
const result = fetch('url/to/api').then(response => response.json()); console.log(result.then(data => console.log(data))); // 上面的代码会抛出类似“Cannot read properties of undefined (reading 'then')”这样的错误 // 因为result这个变量代表的是fetch函数的返回值,而不是json()方法的返回值
应该修改为:
fetch('url/to/api') .then(response => response.json()) .then(data => console.log(data));