问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

js如何调用api接口数据

创作时间:
作者:
@小白创作中心

js如何调用api接口数据

引用
1
来源
1.
https://docs.pingcode.com/baike/2327897

在JavaScript中调用API接口数据,可以使用XMLHttpRequest、Fetch API、或第三方库如Axios。推荐使用Fetch API,因为它是现代浏览器中原生支持的更简单、更灵活的方式。以下详细介绍Fetch API的使用方法。

Fetch API 提供了一个 JavaScript 接口,用于访问和操控 HTTP 管道的一些具体部分,比如请求和响应。它是现代浏览器中原生支持的功能,设计用于替代旧的XMLHttpRequest对象。Fetch API 提供了更简单和更强大的方法来处理HTTP请求和响应。

一、FETCH API简介

Fetch API 是一种基于 Promise 的机制,它使用起来比传统的 XMLHttpRequest 要简单得多。Fetch 方法返回一个 Promise 对象,该对象包含代表请求结果的 Response 对象。可以使用

.then()

.catch()

方法来处理响应和错误。


fetch('https://api.example.com/data')  

  .then(response => response.json())  

  .then(data => console.log(data))  

  .catch(error => console.error('Error:', error));  

二、FETCH API基本使用

1、发送GET请求

GET 请求用于从服务器获取数据。在 Fetch API 中,可以直接调用

fetch

方法,并传入 URL 即可。


fetch('https://api.example.com/data')  

  .then(response => response.json()) // 解析 JSON 格式的响应数据  

  .then(data => {  

    // 处理数据  

    console.log(data);  

  })  

  .catch(error => {  

    // 处理错误  

    console.error('Error:', error);  

  });  

2、发送POST请求

POST 请求用于向服务器提交数据。在 Fetch API 中,需要在

fetch

方法中传入第二个参数对象,指定请求方法和请求体。


fetch('https://api.example.com/data', {  

  method: 'POST',  

  headers: {  

    'Content-Type': 'application/json'  

  },  

  body: JSON.stringify({  

    name: 'John',  

    age: 30  

  })  

})  

  .then(response => response.json())  

  .then(data => {  

    // 处理数据  

    console.log(data);  

  })  

  .catch(error => {  

    // 处理错误  

    console.error('Error:', error);  

  });  

三、处理错误和异常

处理错误和异常是调用API时的重要部分。可以在

.catch

方法中捕获网络错误和异常,并在

.then

方法中检查响应状态码。


fetch('https://api.example.com/data')  

  .then(response => {  

    if (!response.ok) {  

      throw new Error('Network response was not ok ' + response.statusText);  

    }  

    return response.json();  

  })  

  .then(data => console.log(data))  

  .catch(error => console.error('There has been a problem with your fetch operation:', error));  

四、处理不同类型的响应数据

Fetch API 可以处理多种不同类型的响应数据,例如 JSON、文本、Blob、ArrayBuffer 等。


// 处理文本响应  

fetch('https://api.example.com/data')  

  .then(response => response.text())  

  .then(text => console.log(text))  

  .catch(error => console.error('Error:', error));  

// 处理 Blob 响应  

fetch('https://api.example.com/image')  

  .then(response => response.blob())  

  .then(blob => {  

    // 创建一个 URL 对象  

    const url = URL.createObjectURL(blob);  

    // 创建一个 img 元素  

    const img = document.createElement('img');  

    img.src = url;  

    document.body.appendChild(img);  

  })  

  .catch(error => console.error('Error:', error));  

五、并行处理多个请求

有时需要并行处理多个请求,可以使用

Promise.all

方法来实现。


const urls = [  

  'https://api.example.com/data1',  

  'https://api.example.com/data2',  

  'https://api.example.com/data3'  

];  

Promise.all(urls.map(url => fetch(url).then(response => response.json())))  

  .then(results => {  

    // 处理所有请求的结果  

    console.log(results);  

  })  

  .catch(error => {  

    // 处理错误  

    console.error('Error:', error);  

  });  

六、使用Async/Await

使用

async/await

语法可以使代码看起来更加简洁和易读。


async function fetchData() {  

  try {  

    const response = await fetch('https://api.example.com/data');  

    if (!response.ok) {  

      throw new Error('Network response was not ok ' + response.statusText);  

    }  

    const data = await response.json();  

    console.log(data);  

  } catch (error) {  

    console.error('There has been a problem with your fetch operation:', error);  

  }  

}  

fetchData();  

七、使用第三方库Axios

虽然 Fetch API 是现代浏览器的原生功能,但在某些情况下,使用第三方库如 Axios 可能更方便。Axios 是一个基于 Promise 的 HTTP 客户端,具有丰富的功能和更好的浏览器兼容性。

1、安装Axios

可以使用 npm 或 yarn 安装 Axios。


npm install axios  

## **或者**  

yarn add axios  

2、基本使用


const axios = require('axios');  

axios.get('https://api.example.com/data')  

  .then(response => {  

    // 处理数据  

    console.log(response.data);  

  })  

  .catch(error => {  

    // 处理错误  

    console.error('Error:', error);  

  });  

通过本文的详细介绍,希望您能更好地理解和应用JavaScript中的API接口调用技术。无论是使用Fetch API还是第三方库,如Axios,都可以帮助您更加高效地进行前端开发。

© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号