fetch()发送GET请求直接传URL,POST需设method、headers和JSON.stringify()的body,表单用FormData;HTTP错误需手动检查response.ok或status。

JavaScript 使用 fetch() 发送 GET 和 POST 请求非常直接,核心是构造正确的请求配置对象(options),并正确处理响应。
发送 GET 请求(最简形式)
GET 请求通常用于获取数据,URL 中可带查询参数。默认就是 GET,无需显式指定。
- 直接传入 URL 字符串即可发起 GET 请求
- 若需添加查询参数,推荐用
URLSearchParams构建,避免手动拼接出错 - 记得用
.then(res => res.json())解析 JSON 响应体(常见情况)
示例:
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('请求失败:', err));
发送 POST 请求(提交 JSON 数据)
POST 一般用于创建或提交数据,需设置请求头、指定方法,并将数据转为 JSON 字符串作为请求体。
-
method: 'POST'必须显式声明 -
headers中设'Content-Type': 'application/json' -
body接收字符串,所以要用JSON.stringify() - 服务端返回的响应同样需要手动解析(如
.json())
示例:
const postData = { title: '我的新文章', body: '这是内容', userId: 1 };
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(postData)
})
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(data => console.log('创建成功:', data))
.catch(err => console.error('提交失败:', err));
处理表单数据(POST + FormData)
上传文件或提交传统表单时,用 FormData 更合适——它会自动设置正确的 Content-Type(multipart/form-data),且浏览器会处理边界(boundary)。
- 创建
new FormData(),用.append()添加字段 - 不需要手动设置
Content-Type头(fetch 会自动设置) - 适合含文件
的表单
示例:
const form = document.querySelector('#myForm');
const formData = new FormData(form);
fetch('/api/submit', {
method: 'POST',
body: formData // 自动处理编码和头部
})
.then(res => res.json())
.then(data => console.log(data));
注意响应状态与错误边界
fetch() 只在**网络异常**(如断网、DNS 失败)时拒绝 Promise;HTTP 错误状态(如 404、500)仍会进入 .then()。因此必须手动检查 response.ok 或 response.status。
-
response.ok等价于response.status >= 200 && response.status - 不要只依赖
catch捕获所有错误,400+ 状态码不会触发它 - 建议统一在第一个
.then()中做状态校验并抛错,让后续catch统一处理
不复杂但容易忽略。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











