Fetch API
fetch 是一个现代的浏览器 API,用于执行网络请求。
Fetch的基本用法
javascript
fetch(url)
.then(response => {
// 处理响应
})
.catch(error => {
// 处理错误
});链式调用的方式使用Fetch API发送GET请求:
javascript
//链式调用的方式使用Fetch API
function btnClick() {
fetch("https://jsonplaceholder.typicode.com/users")
.then(res => {
if (!res.ok) {
throw new Error("请求失败");
}
return res.json();
}).then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
}async/await的方式使用Fetch API发送GET请求:
javascript
//使用 async/await方式使用Fetch API
async function btnClickAsync() {
try {
let res = await fetch("https://jsonplaceholder.typicode.com/user1s");
if (!res.ok) {
throw new Error("请求失败");
}
let data = await res.json();
console.log(data);
}
catch (error) {
console.log(error);
}
}链式调用的方式使用Fetch API发送POST请求:
javascript
function btnClick() {
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"title": "foo",
"body": "bar",
"userId": 1
})
}).then(res => {
if (!res.ok) {
throw new Error("请求失败");
}
return res.json();
}).then(res => {
console.log(res);
}).catch(error => {
console.log(error);
});
}aysnc/await方式使用Fetch API发送POST请求:
javascript
async function btnClickAsync() {
try {
let res = await fetch("https://jsonplaceholder.typicode.com/user1s", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
"title": "foo",
"body": "bar",
"userId": 1
})
});
if (!res.ok) {
throw new Error("请求失败");
}
let data = await res.json();
console.log(data);
}
catch (error) {
console.log(error);
}
}