闽公网安备 35020302035485号
在现代 web 开发中,从 API 获取数据是一项常见任务。实现的方法也有不少,包括 Axios、原生 Fetch API 以及 Angular 的 HttpClient 库,等等。今天,我们将探讨如何使用题目中的这些工具获取数据,本文不但列出了标准的应用程序代码,还给出了错误处理的示例。一起来学习一下吧。
数据获取是 web 应用程序的关键部分,这是一个从服务器检索数据并集成到 app 的过程。虽然我们有内置的 Fetch API,但别忘了还有诸如 Axios 这样的库,以及诸如 Angular 这样的框架,它们具有更直接的语法,可以为我们提供额外的功能。了解的越多,涉猎的越广,开发人员才能在需要的时候,挑选出最适合特定需求的工具。
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// 堆代码 duidaima.com
// 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 中的错误处理// 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}`);
}
// 堆代码 duidaima.com
// 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();
三. Axiosnpm install axios3.2 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 的 Axiosasync 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 中的错误处理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();
四. Angular HttpClientimport { 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 基本用法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 中的错误处理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);
}
);
}
}
五. 其他数据获取方法$.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 请求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();
Angular HttpClient:集成 Angular,具有强大的 TypeScript 支持,结构化的错误处理。