javascript如何发送请求_fetch api怎么用

Fetch API 是 JavaScript 发送网络请求最常用、现代的方式,基于 Promise,需手动解析 response.json() 并检查 response.ok 以处理 4xx/5xx 错误,支持 async/await 语法提升可读性。

JavaScript 发送网络请求,最常用、现代的方式就是 Fetch API。它基于 Promise,语法简洁,取代了老旧的 XMLHttpRequest(XHR),是目前浏览器原生支持的标准方案。

基本用法:GET 请求

最简单的场景是获取数据(比如从 JSON 接口读取用户列表):

fetch() 接收一个 URL 字符串,返回一个 Promise,成功时 resolve 一个 Response 对象(不是直接的数据!):

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response.json(); // 注意:要手动解析 JSON
  })
  .then(data => console.log(data))
  .catch(err => console.error('请求失败:', err));

发送 POST 请求(带 JSON 数据)

提交表单或调用接口时常用。关键点:设置 headersbody

  • Content-Type 必须设为 application/json
  • body 要用 JSON.stringify() 转成字符串
  • method 显式写为 'POST'
const postData = { title: 'Hello', body: 'World', userId: 1 };

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));

处理错误和状态码

注意:fetch 不会因 4xx/5xx 状态码自动 reject,它只在网络完全失败(如断网、DNS 错误)时才进 catch。所以得手动检查 response.okresponse.status

  • response.ok 是布尔值,等价于 status >= 200 && status
  • 404、500 等响应仍会走 then,需在 then 里判断并 throw 错误,才能被后续 catch 捕获

使用 async/await 写法(更清晰)

配合 async 函数,代码更接近同步逻辑,易读易维护:

async function getUser(id) {
  try {
    const res = await fetch(`/api/users/${id}`);
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const user = await res.json();
    return user;
  } catch (err) {
    console.error('加载用户失败:', err);
    throw err;
  }
}

// 调用
getUser(123).then(u => console.log(u));

基本上就这些。Fetch API 不复杂但容易忽略 response 解析和错误判断细节。用熟了比封装过的库更轻量、更可控。