当前位置: 首页 > article >正文

Web API 哪家强?Axios、Fetch 和 HttpClient 优选指南

在现代 web 开发中,从 API 获取数据是一项常见任务。实现的方法也有不少,包括 Axios、原生 Fetch API 以及 Angular 的 HttpClient 库,等等。

今天,我们将探讨如何使用题目中的这些工具获取数据,本文不但列出了标准的应用程序代码,还给出了错误处理的示例。

一起来学习一下吧。

1. 数据获取

数据获取是 web 应用程序的关键部分,这是一个从服务器检索数据并集成到 app 的过程。

虽然我们有内置的 Fetch API,但别忘了还有诸如 Axios 这样的库,以及诸如 Angular 这样的框架,它们具有更直接的语法,可以为我们提供额外的功能。

了解的越多,涉猎的越广,开发人员才能在需要的时候,挑选出最适合特定需求的工具。

图片

2. Fetch API

Fetch API 提供了一种在 JavaScript 中发出 HTTP 请求的原始方法。因为是内置于浏览器的,所以不需要其他库。

2.1 Fetch 基本用法

使用 Fetch 从 远程 API 获取数据的基本示例:

fetch('https://jsonplaceholder.typicode.com/posts')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

 

2.2 使用 async/await  的 Fetch

使用asyncawait可以使代码更简洁、更具可读性哦:

// Function to fetch data using async/await
async function fetchData() {
  try {
    // Await the fetch response from the API endpoint
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    
    // Check if the response is ok (status in the range 200-299)
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    
    // Await the JSON data from the response
    const data = await response.json();
    
    // Log the data to the console
    console.log(data);
  } catch (error) {
    // Handle any errors that occurred during the fetch
    console.error('Fetch error:', error);
  }
}

// Call the function to execute the fetch
fetchData();

2.3 Fetch 中的错误处理

Fetch 中的错误处理需要检查响应对象的ok属性。错误消息越具体,越能提供 HTTP 状态代码等其他详细信息,也越能更好地进行调试。

// Function to fetch data with explicit error handling
async function fetchWithErrorHandling() {
  try {
    // Await the fetch response from the API endpoint
    const response = await fetch('https://jsonplaceholder.typicode.com/posts');
    
    // Check if the response was not successful
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    
    // Await the JSON data from the response
    const data = await response.json();
    
    // Log the data to the console
    console.log(data);
  } catch (error) {
    // Handle errors, including HTTP errors and network issues
    console.error('Fetch error:', error.message);
  }
}

// Call the function to execute the fetch
fetchWithErrorHandling();

3. Axios

这是一个用于发出 HTTP 请求的流行库。它之所以受欢迎是因为它不但简化了流程,而且比 Fetch API 提供了额外的功能。

3.1 安装 Axios

使用 Axios 之前,我们需要通过npm进行安装或通过 CDN 包含:

npm install axios 

3.2 Axios 的基本用法

使用 Axios 获取数据的基本示例:

const axios = require('axios');

axios.get('https://jsonplaceholder.typicode.com/posts')
  .then(response => console.log(response.data))
  .catch(error => console.error('Error:', error)); 

3.3 使用 async/await 的 Axios

Axios 与asyncawait配合得相当有默契:

async function fetchData() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log(response.data);
  } catch (error) {
    console.error('Axios error:', error);
  }
}

fetchData(); 

3.4 Axios 中的错误处理

Axios 提供了开箱即用的错误处理,赞:

async function fetchWithErrorHandling() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    console.log(response.data);
  } catch (error) {
    if (error.response) {
      // Server responded with a status other than 2xx
      console.error('Error response:', error.response.status, error.response.data);
    } else if (error.request) {
      // No response was received
      console.error('Error request:', error.request);
    } else {
      // Something else caused the error
      console.error('Error message:', error.message);
    }
  }
}

fetchWithErrorHandling();

4. Angular HttpClient

Angular 提供内置的HttpClient模块,可以更轻松地在 Angular 应用程序中执行 HTTP 请求。

4.1 在 Angular 设置 HttpClient

首先我们需要导入HttpClientModule到 Angular 模块(通常是AppModule)。

import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule // Import HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

4.2 HttpClient 基本用法

使用 HttpClient 获取数据的基本示例如下。注意,注入HttpClient的位置是在你想要组件或服务发出 HTTP 请求的地方。

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get('https://jsonplaceholder.typicode.com/posts').subscribe(
      (data) => {
        console.log(data); // Handle data
      },
      (error) => {
        console.error('Angular HTTP error:', error); // Handle error
      }
    );
  }
}

4.3 HttpClient 中的错误处理

Angular HttpClient 提供的错误处理方法更为结构化,更有条理性:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, throwError } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  posts: any[] = [];

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.http.get<any[]>('https://jsonplaceholder.typicode.com/posts')
      .pipe(
        catchError(error => {
          console.error('Error:', error); // Log the error to the console
          // Optionally, you can handle different error statuses here
          // For example, display user-friendly messages or redirect to an error page
          return throwError(() => new Error('Something went wrong; please try again later.'));
        })
      )
      .subscribe(
        data => {
          this.posts = data; // Handle successful data retrieval
        },
        error => {
          // Handle error in subscription if needed (e.g., display a message to the user)
          console.error('Subscription error:', error);
        }
      );
  }
}

5. 其他数据获取方法

除了 Fetch、Axios 和 Angular HttpClient 之外,我们再来介绍几个可以在 JavaScript 中获取数据的库和方法:

5.1 jQuery AJAX

jQuery 提供发出 HTTP 请求的ajax方法,但是呢,我们在现代应用程序中不大能见到它的身影:

$.ajax({
  url: 'https://jsonplaceholder.typicode.com/posts',
  method: 'GET',
  success: function(data) {
    console.log(data);
  },
  error: function(error) {
    console.error('jQuery AJAX error:', error);
  }
});

5.2 XMLHttpRequest 请求

也可以使用比较老的XMLHttpRequest,当然也比较啰嗦:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts');
xhr.onload = function() {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(JSON.parse(xhr.responseText));
  } else {
    console.error('XMLHttpRequest error:', xhr.statusText);
  }
};
xhr.onerror = function() {
  console.error('XMLHttpRequest error:', xhr.statusText);
};
xhr.send();

6. 总结

在 Fetch、Axios 和 Angular HttpClient 之间该如何选择取决于我们具体的项目要求:

  • Fetch API:JavaScript 原生,无其他依赖项,需手动错误处理。

  • Axios:语法更简单,内置错误处理,具有请求取消和拦截器等附加功能。

  • Angular HttpClient:集成 Angular,具有强大的 TypeScript 支持,结构化的错误处理。

总而言之,对于比较简单的项目,或者关键是最少化依赖项时,选择Fetch API 恰到好处。对于需要强大功能和更直观语法的大型项目,Axios 当仁不让。而如果是 Angular 应用程序,考虑到 HttpClient 的集成,以及其他特定于 Angular 的功能,使用 HttpClient 绝对一箭双雕。

只有了解了这些方法的区别,我们才能做出英明抉择,使用最佳工具来完成特定的数据获取任务。


http://www.kler.cn/news/368746.html

相关文章:

  • 数据对齐的大/小端存放示例
  • maven之pom.xml文件解读
  • pip在ubuntu下换源
  • 解读数字化转型的敏捷架构:从理论到实践的深度分析
  • P11229 [CSP-J 2024] 小木棍(民间数据)
  • Java 项目 Dockerfile 示例:从基础镜像选择到环境变量配置的详细指南
  • html5中获取元素的方法
  • 高效集成:聚水潭奇门至金蝶云星空的数据流自动化
  • Python爬虫-汽车投诉排行榜单数据
  • xss跨站及绕过与防护
  • Spring Boot 架构入门学习指南
  • NameNode的HA特性和基于ZKFC的自动故障转移机制
  • 前端浏览器知识总结
  • STM32 第18章 SysTick--系统定时器
  • kafka-console-ui的简介及安装使用
  • OceanMind海睿思受邀参加中国信通院2024数据要素发展大会
  • 使用 Spring Doc 为 Spring REST API 生成 OpenAPI 3.0 文档
  • Web做题思路
  • python实现数据库两个表之间的更新操作(模糊匹配)示例
  • Django-cookie,session
  • 工作中用到的 Linux 总结(持续更新中...)
  • Word 删除空白页:亲测有效的方法
  • 【JavaEE】【多线程】线程池
  • 理解BERT的词向量及其初始化参数的一致性
  • Redis 集群 总结
  • 单片机中的BootLoader(使用汇编指令进行跳转)