Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js fetch的用法

作者:寂寞味道   发布日期:2026-07-16   浏览:81

// 使用 fetch 发起 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); // 处理返回的数据
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

// 使用 fetch 发起 POST 请求
const postData = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
};

fetch('https://api.example.com/posts', postData)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data); // 处理返回的数据
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

解释说明:

  1. GET 请求:

    • fetch('https://api.example.com/data') 发起一个 GET 请求到指定的 URL。
    • .then(response => { ... }) 处理响应。首先检查响应是否成功 (response.ok),然后将响应体解析为 JSON 格式。
    • .catch(error => { ... }) 捕获并处理可能发生的错误。
  2. POST 请求:

    • postData 是一个包含请求方法、头部信息和请求体的对象。
    • fetch('https://api.example.com/posts', postData) 发起一个 POST 请求,并传递 postData 作为配置。
    • 其他部分与 GET 请求类似,处理响应和错误。

上一篇:nodejs fetch

下一篇:js fetch

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站