Fetch
[TOC]
索引
Fetch
方法:
- window.fetch():
(url, options?)
,用于发起网络请求的现代 API,基于 Promise 设计,取代了传统的 XMLHttpRequest。
Response
属性:
方法:
- response.json():
()
, - response.text():
()
, - response.blob():
()
, - response.arrayBuffer():
()
, - response.fromData():
()
,
Fetch
方法
fetch()@
window.fetch():(url, options?)
,用于发起网络请求的现代 API,基于 Promise 设计,取代了传统的 XMLHttpRequest。
url:
string | Request
,指定请求的目标 URL 或预配置的 Request 实例。options?:
{}
,配置请求的选项对象(如请求方法、请求头、请求体等)。- method?:
GET|POST|PUT|DELETE|PATCH
,默认:GET
,HTTP请求方法。 - headers?:
object | Headers
,请求头信息。 - body?:
string|Blob|FormData
,请求体数据(GET 或 HEAD 请求不能包含 body)。 - mode?:
cors|no-cors|same-origin
,默认:cors
,请求模式 - credentials?:
omit|same-origin|include
,默认:same-origin
,是否发送凭据(cookie)。omit
:不发送。same-origin
:同源发送。include
:始终发送。
- cache?:
default|no-store|no-cache|reload|...
,缓存策略。 - redirect?:
follow|error|manual
,重定向处理方式。follow
:自动跟随error
:报错manual
:手动处理
- signal?:
AbortSignal
,用于取消请求的 AbortSignal 对象(结合 AbortController 使用)。
- method?:
返回:
result:
Response
,Promise 对象,解析为 Response 对象。- 常见属性:
- status:HTTP 状态码(如
200
,404
)。 - statusText:状态描述(如
OK
,Not Found
)。 - headers:响应头信息(可通过
headers.get('Content-Type')
获取)。 - ok:布尔值,表示状态码是否在
200-299
范围内。 - 常见方法:
- json():解析响应体为 JSON 对象。
- text():解析响应体为字符串。
- blob():解析响应体为
Blob
对象。 - formData():解析响应体为
FormData
对象。 - arrayBuffer():解析响应体为
ArrayBuffer
对象。
特性:
错误处理:
- HTTP 错误状态码:
fetch
不会因 HTTP 错误状态码(如404
,500
)而拒绝 Promise,需手动检查response.ok
。
jsfetch(url) .then(response => { if (!response.ok) throw new Error(`HTTP 错误:${response.status}`); return response.json(); });
- 网络错误:如请求无法到达服务器,Promise 会被拒绝。
- HTTP 错误状态码:
CORS 限制:
- 跨域请求需服务器设置
Access-Control-Allow-Origin
响应头。 - 非简单请求(如
POST
带非标准头)会触发预检请求(Preflight)。
- 跨域请求需服务器设置
兼容性:所有现代浏览器均支持
fetch
,但旧版浏览器(如 IE)需使用 Polyfill(如whatwg-fetch
)。
示例:
基本使用-GET
js// 字符串形式 fetch('https://api.example.com/data'); // Request 对象形式 const request = new Request('https://api.example.com/data', { method: 'GET' }); fetch(request);
基本使用-POST
jsfetch('https://api.example.com/data', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer xyz' }, body: JSON.stringify({ key: 'value' }), credentials: 'include', mode: 'cors' });
链式处理示例
jsfetch('https://api.example.com/data') .then(response => { if (!response.ok) throw new Error('请求失败'); return response.json(); }) .then(data => console.log(data)) .catch(error => console.error('错误:', error));
完整示例:考虑各种边界判断
jsasync function fetchData(url) { try { const response = await fetch(url, { method: 'GET', headers: { 'Accept': 'application/json' }, credentials: 'include' }); if (!response.ok) throw new Error(`HTTP 错误:${response.status}`); const data = await response.json(); console.log(data); } catch (error) { console.error('请求失败:', error); } } fetchData('https://api.example.com/data');
取消请求:使用 AbortController 中止正在进行的请求
jsconst controller = new AbortController(); const signal = controller.signal; fetch('https://api.example.com/data', { signal }) .then(response => response.json()) .catch(error => { if (error.name === 'AbortError') console.log('请求已取消'); }); // 取消请求 controller.abort();
上传文件:通过 FormData 发送文件。
jsconst formData = new FormData(); formData.append('file', fileInput.files[0]); fetch('https://api.example.com/upload', { method: 'POST', body: formData });
处理流数据:逐步读取大文件或流。
readableStream.getReader():
(options?)
,创建一个读取器并将流锁定于其上。一旦流被锁定,其他读取器将不能读取它,直到它被释放。jsfetch('https://api.example.com/large-file') .then(response => { const reader = response.body.getReader(); return new ReadableStream({ start(controller) { function push() { reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } controller.enqueue(value); push(); }); } push(); } }); }) .then(stream => new Response(stream)) .then(response => response.text()) .then(text => console.log(text));
Response
属性
ok@【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
status【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
statusText【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
headers@【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
body@【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
方法
json()@【
response.json():()
,
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
text()【
response.text():()
,
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
blob()【
response.blob():()
,
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
arrayBuffer()【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js
fromData()【
:``,
:``,
:``,
返回:
:``,
基本示例:
****:
js
核心特性:
****:
js****:
js****:
js
进阶示例:
****:
js****:
js****:
js