MST
星途 面试题库

面试题:JavaScript中如何使用fetch进行API调用并处理返回的JSON数据

假设存在一个API地址为'https://example.com/api/data',该API返回JSON格式的数据。请使用JavaScript的fetch API进行调用,并将返回数据中的某个属性值打印出来。同时,处理可能出现的网络错误。
17.1万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
fetch('https://example.com/api/data')
 .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
 .then(data => {
    // 假设要打印的属性是 'exampleProperty'
    console.log(data.exampleProperty); 
  })
 .catch(error => {
    console.error('Error:', error);
  });