目录
1.API
fetch(url, { // url: 请求地址
// 请求的方法POST/GET等
method: "GET",
// 请求头
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
// 请求发送的数据 blob、BufferSource、FormData、URLSearchParams(get或head方法中不能包含body)
body: '',
// 是否缓存这个请求
cache: 'default',
//要不要携带 cookie 默认不携带 omit、same-origin 或者 include
credentials: 'same-origin',
/*
mode,给请求定义一个模式确保请求有效
same-origin:只在请求同域中资源时成功,其他请求将被拒绝(同源策略)
cors : 允许跨域,通常用作跨域请求来从第三方提供的API获取数据
cors-with-forced-preflight:在发出实际请求前执行preflight检查
no-cors : 目前不起作用(默认)
*/
mode: "",
}).then((res) => {
/*
resp.type // 包含Response的类型 (例如, basic, cors).
resp.url // 包含Response的URL.
resp.status // 状态码
resp.ok // 表示 Response 的成功还是失败
resp.headers // 包含此Response所关联的 Headers 对象 可以使用
resp.clone() // 创建一个Response对象的克隆
resp.arrayBuffer() // 返回一个被解析为 ArrayBuffer 格式的promise对象
resp.blob() // 返回一个被解析为 Blob 格式的promise对象
resp.formData() // 返回一个被解析为 FormData 格式的promise对象
resp.json() // 返回一个被解析为 Json 格式的promise对象
resp.text() // 返回一个被解析为 Text 格式的promise对象
*/
// 根据数据类型转换数据
if (res.status === 200) {
// return resp.json();
// ...
return res.text();
}
// 注: 这里的 resp.json() 返回值不是 js对象,通过 then 后才会得到 js 对象
throw New Error('false of json');
}).then((data) => {
//获取到的数据
console.log(data);
}).catch((error) => {
consolr.log(error);
})
2.GET请求
2.1 请求html数据:res.text()
fetch("http://127.0.0.1:5500/src/fetch.html")
.then((res) => {
return res.text();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
打印结果
2.2 请求image数据:res.blob()
const imgUrl = ref();
fetch("/delete.png")
.then((res) => {
return res.blob();
})
.then((data) => {
imgUrl.value = URL.createObjectURL(data);
})
.catch((error) => {
console.log(error);
});
渲染结果
2.3 请求json数据:res.json()
fetch("/data.json")
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
打印结果
3.POST请求
3.1 提交json数据
fetch("/login", {
method: "POST",
headers: {
"Content-Type": "application/json", // 根据实际情况设置请求头
},
body: JSON.stringify({
userName: "zhangsan",
passWord: "123456",
}),
})
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
3.2 提交表单数据
fetch("/submit", {
method: "POST",
body: new FormData(form)
})
.then((res) => {
return res.json();
})
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});