fetch案例
fetch API
当接收到一个代表错误的 HTTP 状态码时,从 fetch() 返回的 Promise 不会被标记为 reject,即使响应的 HTTP 状态码是 404 或 500。相反,它会将 Promise 状态标记为 resolve(如果响应的 HTTP 状态码不在 200 - 299 的范围内,则设置 resolve 返回值的 ok 属性为 false),仅当网络故障时或请求被阻止时,才会标记为 reject。
fetch 不会发送跨域 cookie,除非你使用了 credentials 的初始化选项
Fetch 是一个 API,它是真实存在的,它是基于 promise 的。
Fetch请求是一种现代Web API,用于在JavaScript中发出HTTP数据请求。它是XMLHttpRequest的一种替代方案,提供了更加简洁和现代化的方式来处理网络请求。Fetch函数是原生JavaScript的一部分,不需要使用XMLHttpRequest对象。Fetch请求使用Promise来处理异步操作,这使得它的代码更加清晰和简洁。
<body>
<script>
function ajaxFetch(url) {
fetch(url).then(res => res.json()).then(data => {
console.info(data)
})
}
ajaxFetch('https://smallpig.site/api/category/getCategory')
</script>
</body>
fetch("http://example.com/movies.json")
.then((response) => response.json())
.then((data) => console.log(data));
// Example POST method implementation:
async function postData(url = "", data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, *cors, same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json",
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data), // body data type must match "Content-Type" header
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData("https://example.com/answer", { answer: 42 }).then((data) => {
console.log(data); // JSON data parsed by `data.json()` call
});
// Fetch 实现
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // 这也是一个Promise
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));