贝利信息

如何使用JavaScript的Fetch API获取数据?

日期:2025-12-14 00:00 / 作者:幻影之瞳
Fetch API 通过 fetch() 发起请求并处理 Promise,需手动检查 response.ok、设置 headers 和 body(如 POST 时用 JSON.stringify),注意 cookies 需 credentials: 'include',且受 CORS 限制。

使用 Fetch API 获取数据很简单,核心是调用 fetch() 函数并处理返回的 Promise。

基本用法:GET 请求获取 JSON 数据

大多数场景下,你只需要发起一个 GET 请求并解析 JSON 响应:

示例:

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
    return response.json();
  })
  .then(data => console.log(data.title))
  .catch(err => console.error('加载失败:', err));

使用 async/await 写法更清晰

配合 async 函数,代码可读性更高,错误处理也更直观:

async function fetchPost() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const data = await response.json();
    console.log(data.title);
  } catch (err) {
    console.error('请求出错:', err.message);
  }
}
fetchPost();

发送 POST 请求并提交数据

需要设置 methodheadersbody 选项:

const postData = { title: 'Hello', body: 'World' };
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(postData)
})
.then(res => res.json())
.then(data => console.log(data.id));

常见注意事项

Fetch 不会自动拒绝 HTTP 错误状态(如 404、500),需手动判断 response.ok;它也不会携带 cookies,如需发送 cookie,得加 credentials: 'include';跨域请求受 CORS 限制,服务端必须允许才能成功。

基本上就这些。不复杂但容易忽略细节。