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

js fetch

作者:戮尽逆者   发布日期:2025-07-26   浏览:89

// 使用 fetch 发送 GET 请求
fetch('https://api.example.com/data')
  .then(response => {
    // 检查响应是否成功
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // 将响应解析为 JSON 格式
    return response.json();
  })
  .then(data => {
    // 处理返回的数据
    console.log(data);
  })
  .catch(error => {
    // 捕获并处理错误
    console.error('There was a problem with the 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 was a problem with the fetch operation:', error);
  });

解释说明:

  1. GET 请求:

    • fetch('https://api.example.com/data') 发起一个 GET 请求到指定的 URL。
    • .then(response => { ... }) 接收响应对象,并检查响应是否成功(response.ok)。
    • 如果响应成功,使用 response.json() 将响应体解析为 JSON 格式。
    • 最后,处理解析后的数据或捕获可能发生的错误。
  2. POST 请求:

    • 定义了一个包含请求方法、头部信息和请求体的对象 postData
    • 使用 fetch('https://api.example.com/posts', postData) 发起一个 POST 请求。
    • 同样地,接收响应对象并进行相应的处理。

通过这种方式,你可以轻松地使用 fetch API 进行网络请求。

上一篇:nodejs fetch

下一篇:js sleep函数

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

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

Laravel 中文站