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 获取数据的基本示例:

javascript 复制代码
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可以使代码更简洁、更具可读性哦:

javascript 复制代码
// 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 状态代码等其他详细信息,也越能更好地进行调试。

javascript 复制代码
// 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 包含:

javascript 复制代码
npm install axios 

3.2 Axios 的基本用法

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

javascript 复制代码
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配合得相当有默契:

javascript 复制代码
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 提供了开箱即用的错误处理,赞:

javascript 复制代码
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)。

javascript 复制代码
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 请求的地方。

javascript 复制代码
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 提供的错误处理方法更为结构化,更有条理性:

javascript 复制代码
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方法,但是呢,我们在现代应用程序中不大能见到它的身影:

javascript 复制代码
$.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,当然也比较啰嗦:

javascript 复制代码
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 绝对一箭双雕。

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

相关推荐
brzhang6 小时前
我操,终于有人把 AI 大佬们 PUA 程序员的套路给讲明白了!
前端·后端·架构
止观止7 小时前
React虚拟DOM的进化之路
前端·react.js·前端框架·reactjs·react
goms7 小时前
前端项目集成lint-staged
前端·vue·lint-staged
谢尔登7 小时前
【React Natve】NetworkError 和 TouchableOpacity 组件
前端·react.js·前端框架
Lin Hsüeh-ch'in7 小时前
如何彻底禁用 Chrome 自动更新
前端·chrome
augenstern4169 小时前
HTML面试题
前端·html
张可9 小时前
一个KMP/CMP项目的组织结构和集成方式
android·前端·kotlin
G等你下课10 小时前
React 路由懒加载入门:提升首屏性能的第一步
前端·react.js·前端框架
蓝婷儿10 小时前
每天一个前端小知识 Day 27 - WebGL / WebGPU 数据可视化引擎设计与实践
前端·信息可视化·webgl
然我11 小时前
面试官:如何判断元素是否出现过?我:三种哈希方法任你选
前端·javascript·算法