成都网站建设与推广,生物网站 template,怀化网站优化公司推荐,seo资料站fetch 是啥#xff1f; fetch 函数是 JavaScript 中用于发送网络请求的内置 API#xff0c;可以替代传统的 XMLHttpRequest。它可以发送 HTTP 请求#xff08;如 GET、POST 等#xff09;#xff0c;并返回一个 Promise#xff0c;从而简化异步操作 基本用法
/*
下面是…fetch 是啥 fetch 函数是 JavaScript 中用于发送网络请求的内置 API可以替代传统的 XMLHttpRequest。它可以发送 HTTP 请求如 GET、POST 等并返回一个 Promise从而简化异步操作 基本用法
/*
下面是 fetch 的基本语法
url请求的 URL必需
options一个包含请求配置的对象可选如请求方法、请求头、请求体等。
*/
fetch(url, options).then(response {// 处理响应}).catch(error {// 处理错误});常见选项
参数 options 是一个对象可以包含以下常见属性
method请求方法例如 GET、POST、PUT、DELETE 等。默认是 GET。headers包含请求头的对象通常用于设置 Content-Type 或授权信息。body请求体用于传递数据POST、PUT 请求时。mode请求模式如 cors、no-cors 和 same-origin。credentials指示是否发送 cookies值为 omit默认不发送、same-origin同源发送或 include跨域发送。
GET 示例
fetch(https://api.example.com/data).then(response {if (!response.ok) {throw new Error(Network response was not ok);}return response.json(); // 将响应解析为 JSON}).then(data console.log(data)).catch(error console.error(Fetch error:, error));POST 示例
fetch(https://api.example.com/data, {method: POST,headers: {Content-Type: application/json},body: JSON.stringify({ name: John, age: 30 })
}).then(response response.json()).then(data console.log(data)).catch(error console.error(Fetch error:, error));上传文件
const formData new FormData();
formData.append(file, fileInput.files[0]); // 假设 fileInput 是一个文件输入fetch(https://api.example.com/upload, {method: POST,body: formData
}).then(response response.json()).then(data console.log(data)).catch(error console.error(Fetch error:, error));封装实例 我们可以将常用的数据交互封装为一个函数方便调用 /*** 处理 Fetch如果返回值不符合规范则报错可通过 .catch 获取* param {*} response* returns*/
const handleResponse response response.json().then(json{if(response.ok json.successtrue)return jsonelsereturn Promise.reject(json)
})/*** 通用 FETCH 交互函数POST* param {String} url - 后端地址* param {Object} data - 表单数据* param {Boolean} useJSON - 是否使用 JSON 格式提交* param {Object} headers - 额外的请求头* param {Function} handler - 处理函数默认转换为 JSON 对象*/
window.ajax (url, data, useJSONtrue, headers{}, handlerhandleResponse){let body undefinedif(useJSON){headers[Content-Type] application/jsonbody JSON.stringify(data)}else{if(data){body new FormData()Object.keys(data).forEach(k body.append(k, data[k]))}}return fetch(url, {method:POST, headers, body}).then(handler)
}使用示例
ajax(/api, {name:集成显卡}).then(dconsole.debug(d))