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

js 调用接口

作者:冷空气来袭   发布日期:2025-09-16   浏览:44

// 使用 fetch API 调用接口的示例代码

// 定义要调用的接口 URL
const url = 'https://api.example.com/data';

// 使用 fetch 发起 GET 请求
fetch(url)
  .then(response => {
    // 检查响应状态码是否在 200-299 之间
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    // 解析响应为 JSON 格式
    return response.json();
  })
  .then(data => {
    // 处理解析后的数据
    console.log('成功获取的数据:', data);
  })
  .catch(error => {
    // 处理请求过程中发生的错误
    console.error('请求失败:', error);
  });

// 如果需要发送 POST 请求,可以这样写:
const postData = {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    key1: 'value1',
    key2: 'value2'
  })
};

fetch(url, postData)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log('POST 请求成功返回的数据:', data);
  })
  .catch(error => {
    console.error('POST 请求失败:', error);
  });

解释说明:

  1. GET 请求

    • 使用 fetch 函数发起一个 GET 请求到指定的 URL。
    • response.ok 用于检查 HTTP 响应的状态码是否在 200-299 之间,表示请求成功。
    • response.json() 将响应体解析为 JSON 格式。
    • catch 用于捕获并处理请求过程中可能发生的错误。
  2. POST 请求

    • 发送 POST 请求时,除了 URL 外,还需要指定请求方法 (method: 'POST') 和请求头 (headers)。
    • body 中包含要发送的数据,通常需要将其转换为 JSON 字符串格式。
    • 同样使用 catch 来处理可能的错误。

上一篇:js json to string

下一篇:js foreach index

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

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

Laravel 中文站