Fetch API 发起请求需调用 fetch() 函数传入 URL 和可选配置,返回 Promise,须用 .then() 或 async/await 处理;GET 默认无需指定 method,POST 需设置 headers 和 JSON.stringify() body;URL 参数应使用 URLSearchParams;response.ok 用于判断 HTTP 状态是否成功。

用 Fetch API 发起请求很简单,核心就是调用 fetch() 函数,传入 URL 和可选配置对象,它返回一个 Promise,然后用 .then() 或 async/await 处理响应。
基础 GET 请求写法
最常用的是不带参数的 GET 请求:
-
fetch()默认就是 GET,直接传 URL 即可 - 返回的是 Promise,需用
.then()链式处理或await - 响应体需手动解析(如
response.json()或response.text())
示例:
fetch('https://api.example.com/data').then(response => {
if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));
带请求头和 JSON 数据的 POST 请求
发 POST 时通常要设置 Content-Type,并把 JS 对象转成 JSON 字符串:
立即学习“Java免费学习笔记(深入)”;
-
method: 'POST'显式声明方法 -
headers中指定'Content-Type': 'application/json' -
body必须是字符串,所以用JSON.stringify()
示例:
const data = { username: 'alice', email: 'a@example.com' };fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => console.log(result))
.catch(err => console.error(err));
带查询参数的 GET 请求
URL 参数不能直接拼字符串(易出错),推荐用 URLSearchParams 构造:
- 先创建参数对象,再转成查询字符串
- 确保中文、特殊字符自动编码
- 最后拼到 URL 后面
示例:
const params = new URLSearchParams({page: '1',
limit: '10',
q: '前端'
});
fetch(`/api/search?${params}`)
.then(r => r.json())
.then(console.log);
处理错误和加载状态
Fetch 不会因 HTTP 状态码(如 404、500)拒绝 Promise,只在网络失败时 reject。所以要手动检查 response.ok:
-
response.ok是布尔值,等价于response.status >= 200 && response.status - 网络异常(如断网、域名不存在)才会进
catch - 建议统一判断状态,并给出明确提示
常见写法:
async function getData() {try {
const res = await fetch('/api/data');
if (!res.ok) {
throw new Error(`请求失败: ${res.status} ${res.statusText}`);
}
return await res.json();
} catch (err) {
console.error('出错了:', err.message);
throw err;
}
}


















