Fetch API 提供简洁的 Promise 风格网络请求,支持 GET/POST 等方法,需手动检查响应状态,可结合 AbortController 实现超时控制,推荐用于现代 JavaScript 开发。
Fetch API 是现代 JavaScript 中用于发起网络请求的一种简洁、强大的方式。相比传统的 XMLHttpRequest,它使用 Promise 风格的语法,代码更清晰,也更容易处理异步操作。
fetch() 函数接收一个 URL 或路径作为参数,默认发起 GET 请求,返回一个 Promise。
fetch('https://jsonplaceholder.typicode.com/posts/1') .then(response => response.json()) .then(data => console.log(data));上面代码请求一个 JSON 接口,先调用 response.json() 将响应体解析为 JSON,再输出结果。
fetch() 只有在网络错误时才会 reject Promise,HTTP 状态码如 404 或 500 不会自动触发错误。需要手动检查 response.ok 或 status。
fetch('/api/data') .then(response => { if (!response.ok) { throw new Error(`HTTP ${response.status}`); } return response.json(); }) .then(data => console.log(data)) .catch(err => console.error('请求失败:', err));通过配置 options 对象,可以发送 POST、PUT 等其他方法的请求。
fetch('/api/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: '新文章',
body: '内容内容',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log(data));
注意设置 Content-Type 头,确保服务器正确解析 JSON 数据。
根据服务器要求,可以发送不同格式的数据:
fetch 不支持原生超时,但可以用 Promise.race 实现:
const abort = new AbortController(); setTimeout(() => abort.abort(), 5000); // 5秒超时 fetch('/api/data', { signal: abort.signal }) .then(r => r.json()) .catch(err => { if (err.name === 'AbortError') { console.log('请求超时或被取消'); } else { console.error('其他错误:', err); } });使用 AbortController 可主动中止请求,适合用户离开页面等场景。
基本上就这些。Fetch API 简洁易用,配合 async/await 更加流畅。现代开发中推荐优先使用 fetch 而非传统 Ajax。