Fetch API 是 JavaScript 与后端交互最常用、现代的方式,原生支持、基于 Promise;支持 GET/POST 请求、认证(Cookie 或 Token)、可封装复用,配合 async/await 更简洁。

JavaScript 与后端 API 交互,最常用、现代的方式就是用 Fetch API。它原生支持、语法简洁、基于 Promise,替代了老式的 XMLHttpRequest。
Fetch 基本用法:GET 请求
向后端获取数据,比如拉取用户列表:
- 调用
fetch(url),返回一个 Promise - 用
.then()处理响应,注意response.json()也返回 Promise - 记得用
.catch()捕获网络错误(注意:404、500 等 HTTP 错误不会进 catch,需手动检查response.ok)
fetch('https://api.example.com/users')
.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 数据)
提交表单、创建资源时常用:
- 设置
method: 'POST' - 用
headers告诉后端你发的是 JSON:'Content-Type': 'application/json' - 用
body: JSON.stringify(obj)序列化数据
fetch('https://api.example.com/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: '张三',
email: 'zhang@example.com'
})
})
.then(res => res.json())
.then(data => console.log('创建成功:', data));
处理认证和 Cookie
很多 API 需要登录态或 Token:
立即学习“Java免费学习笔记(深入)”;
- 带 Cookie(如 session 登录):加
credentials: 'include' - 带 Bearer Token:在
headers中加'Authorization': 'Bearer xxx' - 跨域时确保后端允许对应 header(如
Access-Control-Allow-Headers: Authorization)
封装成更易用的函数
重复写 fetch 容易出错,建议简单封装:
- 统一处理错误、JSON 解析、默认 headers
- 支持 GET/POST 快捷调用
- 可扩展拦截器(如自动加 token)
const api = (url, options = {}) => {
const config = {
headers: { 'Content-Type': 'application/json', ...options.headers },
credentials: 'include',
...options
};
return fetch(url, config)
.then(r => {
if (!r.ok) throw new Error(r.statusText);
return r.json();
});
};
// 使用
api('/users').then(users => console.log(users));
api('/login', { method: 'POST', body: JSON.stringify({ u: 'a', p: 'b' }) });
基本上就这些。Fetch 足够轻量灵活,配合 async/await 写起来更清晰。需要更高级功能(如请求取消、缓存、重试)再考虑 Axios 等库。











