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

使用async和await可以使代码更简洁、更具可读性哦:

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 与async和await配合得相当有默契:

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 绝对一箭双雕。

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

相关推荐
北城笑笑7 小时前
Vue 112 ,下篇:前端 dist 还原成 Vue3 + Vite 项目( krpano 全景接入与页面适配实战,Vue2 → Vue3 )
前端·javascript·vue.js·3d·前端框架·vue·webgl
我叫黑大帅8 小时前
搜“张三”把备注也带出来了?不用加高级筛选,如何让一个搜索框实现「选项直达」!
前端·javascript·面试
如夏倾城10 小时前
WAF (Web Application Firewall,Web应用防火墙)
前端·网络·安全·web安全·web app
图扑可视化10 小时前
基于图扑软件智慧制硅厂 Web SCADA 开发实践
前端·三维可视化·scada·hmi·组态软件
前端fighter11 小时前
2026年前端面试题总结(pdf版)
前端·pdf
谢小飞11 小时前
运维加了个参数,我们的网页挂掉了
前端·浏览器
CoderYanger12 小时前
Java EE 进阶:12.Spring AOP(第二弹)
java·前端·数据库·spring boot·spring·java-ee·mybatis
用户693717500138414 小时前
大模型蒸馏到底在蒸什么?一篇文章搞懂知识蒸馏概念
前端·后端·github
徐小夕15 小时前
实测 10 个前端 UI 生成开源 Skill|AI 输出直达上线标准
前端·vue.js·github
tong_li15 小时前
给娃做个 AI 陪写作业助手:LangChain4j 入门(八):AI 知道这字哪课学的(SQLite 结构化查询入门)
前端·langchain