关于fetch的详细用法和参数
Fetch API 详细用法与参数类型
Fetch API 是现代浏览器提供的用于发起网络请求的 JavaScript 接口,它比传统的 XMLHttpRequest 更强大、更灵活。以下是 Fetch API 的详细用法和参数类型说明。
基本语法
fetch(resource, init)
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
});
参数详解
1. resource 参数 (必需)
类型:string | Request 对象
• 可以是一个 URL 字符串
• 也可以是一个已经创建的 Request 对象
// 字符串 URL
fetch('https://api.example.com/data')
// Request 对象
const request = new Request('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ key: 'value' })
});
fetch(request)
2. init 参数 (可选)
类型:Object - 配置对象,包含以下可选属性:
核心配置项
| 属性 | 类型 | 描述 | 默认值 |
|---|---|---|---|
method |
string | HTTP 方法: 'GET', 'POST', 'PUT', 'DELETE' 等 | 'GET' |
headers |
Headers 对象或普通对象 | 请求头 | - |
body |
Blob/BufferSource/FormData/URLSearchParams/USVString | 请求体 | - |
mode |
string | 请求模式: 'cors', 'no-cors', 'same-origin' | 'cors' |
credentials |
string | 是否发送 cookies: 'omit', 'same-origin', 'include' | 'same-origin' |
cache |
string | 缓存模式: 'default', 'no-store', 'reload', etc. | 'default' |
redirect |
string | 重定向处理: 'follow', 'error', 'manual' | 'follow' |
referrer |
string | 来源页 | 'about:client' |
referrerPolicy |
string | 来源策略 | - |
integrity |
string | 子资源完整性值 | - |
keepalive |
boolean | 是否允许请求在页面卸载后继续 | false |
signal |
AbortSignal | 用于取消请求的信号 | - |
详细说明
method - HTTP 请求方法
fetch('https://api.example.com/data', {
method: 'POST' // 可以是 GET, POST, PUT, DELETE, etc.
});
headers - 请求头
// 方式1: 使用 Headers 对象
const headers = new Headers();
headers.append('Content-Type', 'application/json');
// 方式2: 使用普通对象
fetch('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
}
});
body - 请求体(GET/HEAD 请求不能有 body)
// JSON 数据
fetch('https://api.example.com/data', {
method: 'POST',
body: JSON.stringify({ key: 'value' })
});
// FormData (文件上传)
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
});
// URLSearchParams (表单编码)
const params = new URLSearchParams();
params.append('key1', 'value1');
params.append('key2', 'value2');
fetch('https://api.example.com/data', {
method: 'POST',
body: params
});
mode - 请求模式
fetch('https://api.example.com/data', {
mode: 'cors' // 允许跨域请求
});
credentials - 凭证控制
fetch('https://api.example.com/data', {
credentials: 'include' // 包含 cookies
});
signal - 取消请求
const controller = new AbortController();
const signal = controller.signal;
fetch('https://api.example.com/data', { signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('请求被取消');
}
});
// 取消请求
controller.abort();
响应处理
Fetch API 返回的 Promise 解析为 Response 对象,该对象有以下常用属性和方法:
Response 对象属性
| 属性 | 类型 | 描述 |
|---|---|---|
ok |
boolean | 响应是否成功 (状态码 200-299) |
status |
number | HTTP 状态码 |
statusText |
string | 状态文本 |
url |
string | 最终请求 URL (考虑重定向) |
headers |
Headers | 响应头对象 |
redirected |
boolean | 是否经过重定向 |
type |
string | 响应类型: 'basic', 'cors', 'error' 等 |
Response 对象方法
| 方法 | 返回类型 | 描述 |
|---|---|---|
text() |
Promise |
解析为文本 |
json() |
Promise | 解析为 JSON 对象 |
blob() |
Promise |
解析为 Blob 对象 |
arrayBuffer() |
Promise |
解析为 ArrayBuffer |
formData() |
Promise |
解析为 FormData |
clone() |
Response | 创建响应副本 |
示例响应处理
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json(); // 解析为 JSON
})
.then(data => {
console.log(data); // 处理数据
})
.catch(error => {
console.error('Error:', error);
});
完整示例
1. GET 请求
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
2. POST 请求 (JSON)
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
3. 文件上传 (FormData)
const formData = new FormData();
const fileField = document.querySelector('input[type="file"]');
formData.append('file', fileField.files[0]);
formData.append('username', 'user123');
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(result => {
console.log('Success:', result);
})
.catch(error => {
console.error('Error:', error);
});
4. 带超时和取消的请求
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
fetch('https://api.example.com/data', {
signal: controller.signal
})
.then(response => {
clearTimeout(timeoutId);
return response.json();
})
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request timed out');
} else {
console.error('Error:', error);
}
});
常见问题解决方案
1. 处理非 JSON 响应
fetch('https://api.example.com/text-data')
.then(response => {
if (response.headers.get('Content-Type').includes('application/json')) {
return response.json();
} else {
return response.text();
}
})
.then(data => console.log(data));
2. 处理错误状态码
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('There was a problem:', error);
});
3. 带认证的请求
const token = 'your-auth-token';
fetch('https://api.example.com/protected', {
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => response.json())
.then(data => console.log(data));
4. 并发请求 (Promise.all)
const urls = [
'https://api.example.com/data/1',
'https://api.example.com/data/2',
'https://api.example.com/data/3'
];
Promise.all(urls.map(url =>
fetch(url).then(response => response.json())
))
.then(dataArray => {
console.log(dataArray); // 所有请求的结果数组
})
.catch(error => {
console.error('One or more requests failed:', error);
});
浏览器兼容性
Fetch API 在现代浏览器中得到广泛支持,但在以下情况需要注意:
- IE 不支持:IE 完全不支持 Fetch API
- 旧版浏览器:可能需要 polyfill
- Node.js:原生不支持,需要使用
node-fetch或类似库
Polyfill 方案
<script src="https://cdn.jsdelivr.net/npm/whatwg-fetch@3.6.2/dist/fetch.umd.min.js"></script>
或者使用 npm:
npm install whatwg-fetch
然后在代码中引入:
import 'whatwg-fetch';
总结
Fetch API 提供了强大而灵活的网络请求能力,相比传统的 XMLHttpRequest 有以下优势:
- 基于 Promise 的简洁 API
- 更合理的默认行为
- 更好的错误处理机制
- 内置对多种数据格式的支持
- 更现代的请求控制选项
掌握 Fetch API 的详细用法和参数类型,能够帮助开发者更高效地处理现代 Web 应用中的网络请求需求。

浙公网安备 33010602011771号