一、fetch写法
fetch(url,options)
url:请求地址(必输)
options:配置对象(可选)
二、options配置对象的所有属性
1.method 请求方法
fetch(url,{
method:'POST' //默认GET、PUT、DELETE、HEAD、PATCH
})
2.headers 请求头
fetch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'Accept': 'application/json',
'X-Custom-Header': 'custom-value'
}
})
// 或使用 Headers 对象
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
myHeaders.append('Authorization', 'Bearer token123');
fetch(url, { headers: myHeaders })
常用请求头:
Content-Type: 请求体的数据类型
application/json - JSON数据
application/x-www-form-urlencoded - 表单数据
multipart/form-data - 文件上传
text/plain - 纯文本
Authorization: 认证信息
Accept: 客户端接受的响应类型
User-Agent: 客户端信息
Cookie: Cookie信息
3.body 请求体,只有post请求有body,get请求和head请求不能有
fetch(url,{
method:'POST',
body:JSON.Stringfy({name:'tom',age:'25'})
})
//FormData(文件上传)
const formData = new FormData()
formData.append('username', 'lili')
formData.append('file',fileInput.files[0])
fetch(url,{
method:'POST',
body:formData
})
// URLSearchParams(表单数据)
const params = new URLSearchParams();
params.append('name', 'John');
params.append('age', '30');
fetch(url, {
method: 'POST',
body: params
})
// Blob(二进制数据)
fetch(url, {
method: 'POST',
body: new Blob(['Hello World'], { type: 'text/plain' })
})
// 纯文本
fetch(url, {
method: 'POST',
body: 'plain text data'
})
4.cache 缓存模式
fetch('/api/data', {
cache: 'no-store' // 强制刷新,不使用缓存
})
fetch('/api/static', {
cache: 'force-cache' // 优先使用缓存
})
fetch('/api/data', {
cache: 'no-cache' // 使用缓存前验证
})
5.mode 请求模式,是否允许跨域
6.keepalive 保持连接
三、Response 对象的属性
当fetch成功后,返回一个Response对象
fetch(url).then(response => {
// Response对象的属性
console.log(response.ok); // 布尔值,状态码200-299为true
console.log(response.status); // HTTP状态码,如200, 404, 500
console.log(response.statusText); // 状态文本,如"OK", "Not Found"
console.log(response.url); // 响应的URL(可能经过重定向)
console.log(response.type); // 响应类型
console.log(response.redirected); // 是否经过重定向
console.log(response.headers); // Headers对象
console.log(response.body); // ReadableStream
console.log(response.bodyUsed); // body是否已被读取
});
三、Response 对象的方法
fetch(url).then(response => {
// 读取响应体的方法(只能调用一次)
response.json(); // 解析为JSON
response.text(); // 解析为文本
response.blob(); // 解析为Blob(文件、图片)
response.arrayBuffer(); // 解析为ArrayBuffer
response.formData(); // 解析为FormData
// 克隆响应(允许多次读取body)
const clone = response.clone();
});
//完整用法
fetch('https://api.example.com/users', {
method: 'POST', // 请求方法
// 请求头
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123',
'Accept': 'application/json'
},
// 请求体
body: JSON.stringify({
name: 'John',
age: 30
}),
mode: 'cors', // 请求模式
credentials: 'include',// 凭证(Cookie)
cache: 'no-cache', // 缓存模式
redirect: 'follow', // 重定向处理
referrerPolicy: 'no-referrer', // Referrer策略
integrity: '', // 完整性验证
keepalive: false, // 保持连接
})
.then(response => {
// 检查响应
console.log('状态码:', response.status);
console.log('是否成功:', response.ok);
console.log('响应头:', response.headers.get('Content-Type'));
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return response.json();
})
.then(data => {
console.log('数据:', data);
})
.catch(error => {
console.error('错误:', error);
});
console