Fetch基本语句
fetch是原生js的一个api,是一种http数据请求的方式,是XMLHTTPRequest的一中替代方法,跟Ajax没关系。fetch是增的api,所以兼容性不是很好
<script>
//使用fetch发送请求
fetch('https://v1.hitokoto.cn/', {
method: "GET"
}).then(result => {
console.log(result)
}).catch(msg => {
console.log(msg)
});
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>fetch</title>
</head>
<body>
<p id="hitokoto_text">:D 获取中...</p>
</body>
<script>
//使用fetch发送请求
fetch('https://v1.hitokoto.cn', {
//post的话就在这里面填写配置项的内容
}).then(response => response.json())
.then(data => {
console.log(data)
const hitokoto = document.getElementById('hitokoto_text')
hitokoto.innerText = data.hitokoto
}).catch(console.error);
// fetch('https://v1.hitokoto.cn', {
// method: 'GET',
// //设置请求头
// headers: {
// 'Content-Type': 'x-www-form-urlcoded'
// },
// //不管是同源还是跨域都带着cookie信息
// credentials: 'include'
// });
//get和head不能设置body,并且不管服务器返回的状态是什么,fetch都不认为是失败,都会接着执行then方法
</script>
</html>
注意:get和head不能设置body,并且不管服务器返回的状态是什么,fetch都不认为是失败,都会接着执行then方法
//自行解决fetch不管返回什么状态码都执行then的行为
fetch('https://v1.hitokoto.cn').then(result => {
let {
result
} = result;
if (/^(4|5)\d{2}$/.test(status)) {
throw new Error('query data is error!');
return;
}
return result.json();
}).then(result => {
console.log(result)
}).catch(msg => {
console.log(msg)
});