Fetch API 通过 fetch() 发起请求并处理 Promise,需手动检查 response.ok、设置 headers 和 body(如 POST 时用 JSON.stringify),注意 cookies 需 credentials: 'include',且受 CORS 限制。

使用 Fetch API 获取数据很简单,核心是调用 fetch() 函数并处理返回的 Promise。
基本用法:GET 请求获取 JSON 数据
大多数场景下,你只需要发起一个 GET 请求并解析 JSON 响应:
-
fetch()接收一个 URL 字符串,返回一个 Promise - 响应对象需要先调用
.json()(或其他方法如.text()、.blob())才能读取内容 - 记得用
try/catch或.catch()处理网络错误和解析失败
示例:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
return response.json();
})
.then(data => console.log(data.title))
.catch(err => console.error('加载失败:', err));
使用 async/await 写法更清晰
配合 async 函数,代码可读性更高,错误处理也更直观:
立即学习“Java免费学习笔记(深入)”;
async function fetchPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data.title);
} catch (err) {
console.error('请求出错:', err.message);
}
}
fetchPost();
发送 POST 请求并提交数据
需要设置 method、headers 和 body 选项:
-
Content-Type通常设为'application/json' -
body必须是字符串,所以要用JSON.stringify() - 服务器返回后仍需检查
response.ok并解析响应体
const postData = { title: 'Hello', body: 'World' };
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData)
})
.then(res => res.json())
.then(data => console.log(data.id));
常见注意事项
Fetch 不会自动拒绝 HTTP 错误状态(如 404、500),需手动判断 response.ok;它也不会携带 cookies,如需发送 cookie,得加 credentials: 'include';跨域请求受 CORS 限制,服务端必须允许才能成功。
基本上就这些。不复杂但容易忽略细节。










