Axios都说了,那就顺便说一下Fetch吧

Axios文章链接:一文带你理清Axios的有关问题-CSDN博客

Fetch 是浏览器原生提供的用于进行网络请求的 API,它可以用来替代传统的 XMLHttpRequest,并且支持 Promise,使得代码更加简洁。与 Axios 类似,你可以使用 Fetch 发送 GETPOSTPUTDELETE 等请求。下面我会详细讲解 Fetch 的基本用法及其特点。

1. 发送 GET 请求

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 解析 JSON 响应
  })
  .then(data => {
    console.log('Data received:', data); // 处理成功的响应数据
  })
  .catch(error => {
    console.error('Fetch error:', error); // 处理错误
  });
URL 查询参数

查询参数通常附加在 URL 的末尾,格式为 ?key1=value1&key2=value2,多个参数用 & 连接。

 2. 发送 POST 请求

当你想发送数据到服务器时,通常会使用 POST 请求。你需要在请求中指定请求方法和请求体。

fetch('https://api.example.com/login', {
  method: 'POST', // 请求方法
  headers: {
    'Content-Type': 'application/json', // 设置请求头,告诉服务器请求体是JSON格式
  },
  body: JSON.stringify({
    username: 'john_doe',
    password: 'password123',
  }),
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Login failed');
    }
    return response.json();
  })
  .then(data => {
    console.log('Login successful:', data); // 处理成功的登录响应
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

3. PUT 请求

PUT 请求通常用于更新服务器上的资源。

fetch('https://api.example.com/users/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    name: 'John Doe',
    age: 30
  }),
})
  .then(response => response.json())
  .then(data => {
    console.log('Update successful:', data);
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

 PUT 请求的结构与 POST 类似,唯一的不同是方法名,这里是 PUT,用于更新资源。

 4. DELETE 请求

fetch('https://api.example.com/users/1', {
  method: 'DELETE',
})
  .then(response => {
    if (!response.ok) {
      throw new Error('Delete failed');
    }
    console.log('User deleted');
  })
  .catch(error => {
    console.error('Fetch error:', error);
  });

5. 使用 async/await 语法 

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log('Data received:', data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchData();
  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LJ小番茄

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值