上一篇
fetch api 参数
- 行业动态
- 2025-05-02
- 2900
Fetch API参数包括URL、method、headers、body等,通过配置对象传递,支持异步处理网络请求,可
Fetch API 参数详解
参数列表与说明
参数名称 | 类型 | 默认值 | 描述 | 示例 |
---|---|---|---|---|
method | string | 'GET' | HTTP 请求方法(如 POST、PUT、DELETE 等)。 | method: 'POST' |
headers | Headers 对象 | 自定义 HTTP 头(如 Content-Type 、Authorization 等)。 | headers: { 'Content-Type': 'application/json' } | |
body | BodyInit 类型 | null | 请求体数据(仅用于 POST、PUT 等有 body 的请求方法)。 | body: JSON.stringify({ key: 'value' }) |
mode | string | 'same-origin' | 请求模式(cors 、no-cors 、same-origin ),影响跨域行为。 | mode: 'cors' |
credentials | string | 'omit' | 是否发送凭据(如 Cookies),可选值:omit 、same-origin 、include 。 | credentials: 'include' |
cache | string | 'default' | 缓存策略(default 、no-store 、reload 、no-cache 、force-cache )。 | cache: 'no-cache' |
redirect | string | 'follow' | 重定向行为(follow 、error 、manual )。 | redirect: 'manual' |
referrer | string 或 null | 'about:client' | 请求的 Referer 头信息,可设为空字符串或 null 以隐藏来源。 | referrer: '' 或 referrer: null |
integrity | string | undefined | 请求资源的完整性校验(如 sha256-... )。 | integrity: 'sha256-...' |
keepalive | boolean | false | 是否启用持久连接(需浏览器支持)。 | keepalive: true |
signal | AbortSignal 对象 | null | 用于中止请求的信号(配合 AbortController 使用)。 | signal: controller.signal (通过 new AbortController() 创建) |
关键参数详解与示例
method
- 用途:指定 HTTP 方法(如 GET、POST、PUT、DELETE)。
- 示例:
fetch('/api/data', { method: 'POST' });
headers
- 用途:设置请求头(如
Content-Type
、Authorization
)。 - 注意:直接修改
headers
对象会抛出错误,需使用Headers.append()
方法。 - 示例:
const headers = new Headers(); headers.append('Content-Type', 'application/json'); fetch('/api/data', { headers });
- 用途:设置请求头(如
body
- 用途:发送请求体数据(仅用于 POST、PUT 等方法)。
- 支持的类型:
String
、Blob
、Buffer
、ArrayBuffer
、FormData
、URLSearchParams
、ReadableStream
。 - 示例:
fetch('/api/upload', { method: 'POST', body: JSON.stringify({ file: 'data:text/plain,Hello' }), headers: { 'Content-Type': 'application/json' } });
mode
- 用途:控制跨域请求行为。
cors
:允许跨域请求,但需服务器设置Access-Control-Allow-Origin
。no-cors
:仍受同源策略限制,但无 CORS 响应。same-origin
:仅限同源请求。
- 示例:
fetch('https://api.example.com/data', { mode: 'cors' });
- 用途:控制跨域请求行为。
credentials
- 用途:控制是否发送 Cookie 或授权头。
omit
:不发送凭据(默认)。same-origin
:仅同源时发送。include
:总是发送。
- 示例:
fetch('/api/auth', { credentials: 'include' });
- 用途:控制是否发送 Cookie 或授权头。
cache
- 用途:控制缓存策略。
default
:默认缓存行为(可能缓存)。no-store
:禁止缓存。reload
:强制重新验证缓存。no-cache
:强制向服务器验证资源是否更新。force-cache
:仅从缓存获取,不验证。
- 示例:
fetch('/api/data', { cache: 'no-store' });
- 用途:控制缓存策略。
redirect
- 用途:控制重定向行为。
follow
:自动跟随重定向(默认)。error
:将重定向视为错误。manual
:手动处理重定向(需检查response.status
)。
- 示例:
fetch('/api/redirect', { redirect: 'manual' }).then(response => { if (response.status === 307) { // 手动处理重定向逻辑 } });
- 用途:控制重定向行为。
signal
- 用途:配合
AbortController
实现请求中止。 - 示例:
const controller = new AbortController(); fetch('/api/data', { signal: controller.signal }); // 中止请求 controller.abort();
- 用途:配合
注意事项
异步处理
fetch
返回的是一个Promise
,需通过.then()
或async/await
处理结果。- 示例:
fetch('/api/data').then(response => response.json()).then(data => console.log(data));
错误处理
fetch
仅在网络错误时才会reject
,HTTP 状态码错误(如 404)需手动检查。- 示例:
fetch('/api/invalid').then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }).catch(error => console.error('Fetch error:', error));
跨域限制
- 使用
mode: 'cors'
时,需服务器设置Access-Control-Allow-Origin
。 mode: 'no-cors'
会隐藏跨域响应,但无法读取响应体。
- 使用
相关问题与解答
问题 1:如何用 Fetch API 处理 JSON 响应?
解答:
使用 response.json()
方法将响应体解析为 JSON 对象,需注意该方法返回一个 Promise
,因此需要链式调用或使用 async/await
。
示例:
fetch('/api/data') .then(response => response.json()) // 解析为 JSON .then(data => console.log(data)) .catch(error => console.error('Error:', error));
问题 2:如何取消正在进行的 Fetch 请求?
解答:
使用 AbortController
创建一个信号对象,并将其传递给 fetch
的 signal
参数,调用 abort()
方法即可中止请求。
示例:
const controller = new AbortController(); const signal = controller.signal; fetch('/api/data', { signal }).then(response => { // 如果请求被中止,此处不会执行 }); // 触发取消 controller.abort();