JavaScript 和 React 中的 API 处理:从基础到专业级
学习使用 fetch、axios 和错误处理来处理 JavaScript API。API 处理是指向服务器发出 HTTP 请求以获取或发送数据。
大家好,我的前端开发人员朋友们,今天我将讨论 javascript 中最重要的概念之一,api 处理。
- 我将首先在Scribbler.live上创建我的代码片段,这是一个很棒的平台,允许您运行 JavaScript Notebook、在线编译器和编辑器,而无需手动设置。
- 此外,我还附上了包含所有代码示例的代码片段链接,以便您可以打开该片段并自行运行以查看结果。
- 我将使用
scrib.show
scribbler.live,它相当于console.log
- 由于目前它不支持 axios 和 react,因此只有来自 fetch api 的示例才会添加到 scribbler。
让我们深入了解
目录
什么是 API?
- API 是一组允许两个软件组件进行通信的定义和协议。
- 编写api使用的一些技术有:
- Javascript(Express 框架)
- Python(Django框架)
- Go(Gin 框架)
- Java(Spring Boot 框架)
- C#(ASP.NET Core 框架)
什么是 API 处理?
API 处理是指向服务器发出 HTTP 请求以获取或发送数据。在 JavaScript 和 React 中,API 调用通常使用 fetch、Axios 或 React Query 或 TanStack Query 等库来处理。
HTTP 方法
API 可以使用不同的 HTTP 方法,每种方法都有特定的用途:
GET
– 从服务器获取数据。POST
– 向服务器发送新数据。PUT
– 更新现有数据(替换整个资源)。PATCH
– 更新部分现有资源。DELETE
– 从服务器中删除数据。
使用 JavaScript 发出 API 请求
Fetch 方法
原生 fetch API 方法通常用于与 API 交互。它接受两个参数:API 端点和用于传递 headers、body、方法等信息的 options 对象。
使用 GET 请求获取方法
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => scrib.show(data))
.catch(error => scrib.show('Error:', error));
使用 POST 请求获取方法
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST', // type of method GET, POST, PUT, POST, DELETE
headers: {
'Content-Type': 'application/json' // headers like referrer, bearer, content-type, custom headers, etc.
},
// body of the POST request which we are sending to the api
body: JSON.stringify({
title: 'Javascript is awesome',
body: 'Did you know you could write html and javascript combined in scribbler',
userId: 1
})
})
.then(response => response.json())
.then(data => scrib.show(data))
.catch(error => scrib.show('Error:', error));
使用 fetch 方法处理错误
fetch('https://jsonplaceho.typicode.com/posts') // incorrect api endpoint
.then(response => response.json())
.then(data => scrib.show(data))
.catch(error => scrib.show('Error:', error)); // will run this block of code and throws error
使用 try catch finally 块处理 api
async function getData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error('Network response was not ok'); // return boolean for valid/invalid responses
let data = await response.json();
scrib.show(data)
} catch (error) {
scrib.show('Fetch error:', error); // will handle the error if the fetch fails
} finally {
scrib.show(Fetch request is done); // will run no matter a response is valid or invalid or fetch fails
}
}
getData()
查看此嵌入以运行上面提到的代码示例
Axios
Axios 是一个 javascript 库,它简化了 API 处理并提供更好的错误处理。
Axiox 带有 GET 请求
import axios from "axios"
// all http methods could be chained with axios
axios.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => scrib.show(response.data))
.catch(error => scrib.show('Error:', error));
Axios 带 POST 请求
import axios from "axios"
// json body is passed separately as second argument and rest of the options as third argument
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Javascript is awesome',
body: 'Did you know you could write html and javascript combined in scribbler',
userId: 1
}, {
headers: { 'Content-Type': 'application/json' }
})
.then(response => scrib.show(response.data)) // automatically converts the response to json format
.catch(error => scrib.show('Error:', error));
使用 axios 进行错误处理
import axios from "axios"
axios.get('https://jsonpl.typicode.com/posts') // incorrect url
.then(response => scrib.show(response.data))
.catch(error => {
// has multiple error response for different scenarios
if (error.response) {
scrib.show('Server responded with:', error.response.status);
} else if (error.request) {
scrib.show('No response received');
} else {
scrib.show('Error setting up request:', error.message);
}
});
使用 try catch finally 块处理 api
import axios from "axios";
const fetchData = async () => {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
console.log("Data fetched successfully:", response.data);
return response.data;
} catch (error) {
console.error("Error fetching data:", error.response?.data || error.message);
return null;
} finally {
console.log("Fetch is done")
}
};
fetchData();
React(使用 useEffect 和 useState)
import { useEffect, useState } from 'react';
function Posts() {
// Creating states for data and error messages
const [posts, setPosts] = useState([]);
const [error, setError] = useState(null);
// Performing data fetching in useEffect, will run only once on page load
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch');
}
return response.json();
})
.then(data => setPosts(data))
.catch(error => setError(error.message));
}, []);
if (error) return <p>Error: {error}</p>;
return (
<div>
<h2>Posts</h2>
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
}
export default Posts;
Tanstack 查询库
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
// fetch the data and return it
const fetchPosts = async () => {
const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
return data;
};
function Posts() {
// tanstack has builtin data, error, loading states
const { data: posts, error, isLoading } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts });
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
export default Posts;
结论
JavaScript 和 React 中的 API 处理涉及:
- 使用 fetch 或 Axios 进行 API 调用。
- 处理不同的 HTTP 方法(GET、POST、PUT、DELETE)。
- 实施适当的错误处理。
- 管理身份验证的标头。
- 在 React 中使用 useEffect 进行 API 调用。
- 利用 React Query 实现高效的状态管理。
这篇文章就到这里,如果我能改进一下这篇文章,欢迎告诉我。另外,也请关注Scribbler.live网站。
您可以通过以下方式联系我 -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
电子邮件 - shubhmtiwri00@gmail.com
您可以通过以下链接为我提供一些捐款,谢谢
👇👇 https://www.buymeacoffee.com/waaduheck
也请查看这些帖子

MicroFrontend - React | Solid | Vue
Shubham Tiwari ・ 2024年1月9日
#tutorial #webdev #beginners #learning