视频教程: Web前端必会实用技术Fetch
基础使用
let url = "https://baidu.com";
fetch(url)
.then((res) => {
// 返回Response对象的json值(Promise对象)
return res.json();
})
.then((json) => {
// 打印该对象
console.log(json);
}).catch((err) => {
// 出错时打印错误信息
console.log(err);
}).finally(() => {
// 无论如何都会执行的代码
console.log("finally");
})
使用异步函数改写
async function getData(url) {
try {
// 异步获取数据
const res = await fetch(url);
// 返回Promise对象的json值
const json = await res.json();
console.log(json);
} catch ((err) {
console.log(err)
})finally {
// 无论如何都会执行的代码
console.log("finally");
}
}
// 调用getData()函数
getData(url);
查询参数
地址栏拼接参数
let url = "https://baidu.com?id=1";
async function getData(url) {
const res = await fetch(url);
const json = await res.json();
console.log(json);
}
// 调用getData()函数
getData(url);
属性方法
...
const res = await fetch(url);
// 常见属性
res.ok 是否成功 true/false
res.status 状态码 200/404..
res.statusText 状态文本信息
res.headers 头部信息
res.url 请求的url
res.type 请求的类型
res.redirected 是否重定向 true/false
res.redirectedToUrl 重定向的url
res.bodyUsed 是否使用了body
res.body body信息
res.clone() 复制请求
res.json() 返回json数据
res.text() 返回文本数据
res.arrayBuffer() 返回二进制BArrayBuffer数据
res.blob() 返回二进制BBlob数据
res.formData() 返回FormData表单数据
发送其他请求
let res = await fetch(url, {
method: "POST", // DELETE PUT POST GET...
headers: {
"Content-Type": "application/json" // 设置请求头内容类型 json/form-data/text/blob/arraybuffer...
},
body: JSON.stringify({
name: "tmilar",
age: 18
})
})...
封装请求
以json为例
async function http(options) {
let {method,url,params,data} = options;
let res;
// params 需要转为 keyvalue形式的字符串
if(params) {
/* let paramsArray = [];
Object.keys(params).forEach(key => {
paramsArray.push(${key}=${params[key]}
);
}),
url += "?" + paramsArray.join("&");
*/
url = "?" + new URLSearchParams(params).toString();
}
// 如果有 data 就用POST方法,没有就普通GET
if(data) {
res = await fetch(url, {
method: method,
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
}else {
res = await fetch(url);
}
return res.json();
}