- fetch不是AJAX,它诞生的目的是为了代替 ajax,它是JS中内置的API:基于fetch可以实现客户端和服务器端的信息通信:
- fetch是ES2018规范中新增的API,所以浏览器的支持度不是特别好(可以基于BABEL的最新语法解析包,把其进行解析),想要兼容性好一些,需要使用 “fetch polyfill”
- 使用fetch发送请求
=> get/head等请求不能设置body
=> 不管服务器返回的状态是多少,fetch都不认为是失败(那怕是4或者5开头的状态码),都执行的是then中的方法(需要我们自己进行异常抛出处理)
示例
fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/info2', {
method: 'GET',
headers: {
//=>设置请求头
'content-type': 'x-www-form-urlencoded'
},
//=>不管同源还是跨域请求都带着COOKIE信息
credentials: 'include'
}).then(result => {
let {status} = result;//获取状态码,自己判断成功与否
if (/^(4|5)\d{2}$/.test(status)) {
throw new Error('query data is error!');
return;
}
/* headers:{} 包含响应头信息
* redirected:false 是否重定向
* status:状态码
* statusText
* type:'basic'/'cors'
* url:请求的地址
* __proto__:Response
* arrayBuffer()
* blob()
* json()
* text()
* ...
* 基于这些方法可以快速的把从服务器获取的结果找到
*/
})
fetch('https://www.easy-mock.com/mock/5b0412beda8a195fb0978627/temp/add', {
method: 'POST',
body: 'a=1&b=2'//=>BODY中只支持字符串(GET请求还无法设置BODY)
}).then(result => {
let {status} = result;
if (/^(4|5)\d{2}$/.test(status)) {
throw new Error('query data is error!');
return;
}
return result.json();
})
网友评论