有勇气的牛排博客

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

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

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请求案例


留言

专栏
文章
加入群聊