Fetch API 是浏览器内置的现代网络请求接口,基于 Promise,支持 async/await;GET/POST 请求需手动处理 HTTP 错误和 JSON 解析,注意 credentials、超时及进度等限制。
Fetch API 是浏览器内置的、用于发起网络请求的现代 JavaScript 接口,它比传统的 XMLHttpRequest 更简洁、更强大,基于 Promise,天然支持 async/await。
最简单的 fetch 调用只需要传入一个 URL 字符串:

fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('请求失败:', error));
需要配置 options 对象,指定 method、headers 和 body:
const data = { username: 'alice', password: '123' };
fetch('https://api.example.com/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(json => console.log(json))
.catch(err => console.error(err));
配合 async 函数,可以写出接近同步风格的请求逻辑:
async function getUser(id) {
try {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) throw new Error(res.statusText);
const user = await res.json();
return user;
} catch (err) {
console.error('获取用户失败:', err);
throw err;
}
}
// 调用
getUser(123).then(u => console.log(u));
基本上就这些。fetch 简洁够用,日常开发中搭配 async/await 和简单的错误检查,就能覆盖绝大多数场景。