https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
https://www.ruanyifeng.com/blog/2020/12/fetch-tutorial.html
- 比传统ajax更简单,强大,可以看作XHR的升级版
- 基于Promise实现 ```javascript
fetch(‘https://api.github.com/users/ruanyf‘) .then(response => response.json()) .then(json => console.log(json)) //这里才是数据 .catch(err => console.log(‘Request Failed’, err));
- response.text()是字符串
- response.json()是JSON(前提是返回值符合JSON格式)
**请求参数**
- method
- body
- headers
fetch()发出请求以后,有一个很重要的注意点:只有网络错误,或者无法连接时,fetch()才会报错,其他情况都不会报错,而是认为请求成功。<br />这就是说,即使服务器返回的状态码是 4xx 或 5xx,fetch()也不会报错(即 Promise 不会变为 rejected状态)。<br />只有通过Response.status属性,得到 HTTP 回应的真实状态码,才能判断请求是否成功。
```javascript
async function fetchText() {
let response = await fetch('/readme.txt');
if (response.status >= 200 && response.status < 300) {
return await response.text();
} else {
throw new Error(response.statusText);
}
}