什么是Fetch?
Fetch是一种基于 Promise 设计,可以简单、合理地跨网络异步获取资源的JavaScript 接口,号称是AJAX的替代品。
主要优点:
- 符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
- 更好更方便的写法
- 更加底层,提供的API丰富(request, response)
- 脱离了XHR,是ES规范里新的实现方式
why使用:
跟上适应新规范的潮流,程序员最怕掉队
基本使用
fetch('http://localhost:5000/').then(response=>{
if(response.ok){ // 判断是否请求成功
return response.json() // 获取返回的json结果
}else{
return Promise.reject('error') // 请求失败,调用Promise的拒绝方法
}
}).then(result=>{// 输出结果
console,log(result)
}).catch(e=>{ // 处理错误
console.log(e)
})
添加参数
fetch(url, {
body: JSON.stringify(data), // 数据结构必须要与 'Content-Type' 请求头匹配
cache: 'no-cache', // 设置缓存的三种模式 *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // 凭证模式 include, same-origin, *omit
headers: {
'user-agent': 'Mozilla/4.0 MDN Example',
'content-type': 'application/json'
},
method: 'POST', // 请求方法 *GET, POST, PUT, DELETE, etc.
mode: 'cors', // 跨域模式 no-cors, cors, *same-origin
redirect: 'follow', // 重定向 manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}