有勇气的牛排博客
☰

全面理解 fetch 请求:现代 JavaScript 网络请求详解

有勇气的牛排 1447 前端 2022-11-07 15:46:36

知止自律打卡-微信小程序APP
一款微信自律打卡小程序,支持自定义打卡项目、习惯记录、项目日记、专注计时与数据统计。自律打卡、学习打卡、读书打卡、健身打卡、运动打卡、减肥打卡、戒色打卡、养生打卡、戒烟、戒酒、戒熬夜等多种场景。万能打卡模板自由创建。可自定义每日打卡目标,记录习惯连续天数,可视化追踪成长进度。
了解产品详情 →
微信搜索「知止自律打卡」
知止自律打卡微信小程序

1 前言

fetch 是一种现代的前端 Web API,用于发起网络请求并处理响应。它比传统的 XMLHttpRequest 更加简洁、灵活,且基于 Promise 进行异步操作,使得代码更清晰易懂。

2 POST

post封装

async function postData(url, data) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(data)
        });
        if (!response.ok) {
            throw new Error(`HTTP错误:状态码 ${ response.status }`);
        }
        return await response.json();
    } catch (error) {
        console.error('请求失败:', error);
        return null; // 根据需要返回 null 或抛出错误
    }
}

调用

document.getElementById('postBtn').addEventListener('click', async function () {
    const url = "http://127.0.0.1:8090/test_json_post";
    const dataToSend = {
      nickname: '有勇气的牛排'
    };
    
    const data2 = await postData(url, dataToSend);
    console.log(">>> 最终结果");
    console.log(data2);
});

3 GET

<script>
  async function getData(url, params) {
    try {
      // 构建 URL 查询参数字符串
      const urlWithParams = new URL(url);
      Object.keys(params).forEach(key => urlWithParams.searchParams.append(key, params[key]));

      const response = await fetch(urlWithParams, {
        method: 'GET',
        headers: {'Content-Type': 'application/json'}
      });

      if (!response.ok) {
        throw new Error(`HTTP错误:状态码 ${response.status}`);
      }

      return await response.json();
    } catch (error) {
      console.error('请求失败:', error);
      return null; // 根据需要返回 null 或抛出错误
    }
  }

  document.getElementById('getBtn').addEventListener('click', async function () {
    const url = "http://127.0.0.1:8090/test_json";
    const params = {
      nickname: '有勇气的牛排'
    };

    const data = await getData(url, params);
    console.log(">>> 最终结果");
    console.log(data);
  });
</script>

4 通用函数封装

通用函数

// 通用请求函数
async function requestData(url, method = 'GET', data = null) {
    try {
      let options = {
        method: method.toUpperCase(),
        headers: {'Content-Type': 'application/json'}
      };
    
      // 如果是 POST 请求,添加请求体
      if (method === 'POST' && data) {
        options.body = JSON.stringify(data);
      }
    
      // 如果是 GET 请求,将数据作为查询参数添加到 URL 中
      if (method === 'GET' && data) {
        const urlWithParams = new URL(url);
        Object.keys(data).forEach(key => urlWithParams.searchParams.append(key, data[key]));
        url = urlWithParams.toString();
      }
    
      const response = await fetch(url, options);
    
      if (!response.ok) {
        throw new Error(`HTTP错误:状态码 ${response.status}`);
      }
    
      return await response.json();
    } catch (error) {
      console.error('请求失败:', error);
      return null; // 根据需要返回 null 或抛出错误
    }
}

POST

// 用于调用 POST 请求的按钮点击事件
document.getElementById('postBtn').addEventListener('click', async function () {
    const url = "http://127.0.0.1:8090/test_json_post";
    const dataToSend = {
      nickname: '有勇气的牛排'
    };

    const result = await requestData(url, 'POST', dataToSend);
    console.log(">>> POST 请求结果");
    console.log(result);
});

GET

// 用于调用 GET 请求的按钮点击事件
document.getElementById('getBtn').addEventListener('click', async function () {
    const url = "http://127.0.0.1:8090/test_json_get";
    const params = {
      nickname: '有勇气的牛排'
    };

    const result = await requestData(url, 'GET', params);
    console.log(">>> GET 请求结果");
    console.log(result);
});

前端 javascript fetch get请求案例

标签:

×
×