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

js fetch用法

作者:Xn﹏仍嘫佷痌   发布日期:2026-07-03   浏览:109

// 使用 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 请求。
    • .then(response => { ... }) 处理响应,检查响应状态并将其解析为 JSON。
    • .catch(error => { ... }) 捕获并处理请求过程中可能发生的错误。
  2. POST 请求

    • const postData 定义了 POST 请求的配置,包括方法、头部信息和请求体。
    • fetch('https://api.example.com/posts', postData) 发起一个 POST 请求。
    • 同样使用 .then().catch() 来处理响应和错误。

通过这些示例代码,你可以了解如何使用 fetch API 发起 HTTP 请求,并处理响应和错误。

上一篇:js fetch

下一篇:js sleep函数

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站