一、Fetch同步发送GET请求
fetch('http://ajax-base-api-t.itheima.net/api/getbooks').then(res => {
console.log(res);
return res.json();
}).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
})
二、Fetch异步发送GET请求
async function getData() {
let res = await fetch('http://ajax-base-api-t.itheima.net/api/getbooks');
console.log(res);
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.url);
let json = await res.json();
console.log(json);
}
getData();
三、Fetch异步发送POST请求
async function addData() {
let obj = {
bookname: '三国杀2',
author: '马超',
publisher: '特朗普、关羽'
}
let res = await fetch('http://ajax-base-api-t.itheima.net/api/addbook', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(obj)
});
let json = await res.json();
console.log(json);
}
addData();