一、Fetch介绍
- 在jQuery开发时代,jQuery已经为我们封装了非常优雅的ajax函数,并且针对各个浏览器都做好了兼容,非常方便。但是当我们使用React Vue或者angular去开发webpap的时候,我们还会再为了一个ajax去使用jQuery吗?这是一个问题。
- 另外一个问题,JavaScript中的ajax很早之前就有一个诟病,就是复杂业务下的callback嵌套问题。Promise正式js中解决这一问题的钥匙,并且作为标准在ES6中发布,接下来要介绍的fetch就用到了最新的Promise。
- Fetch就是一种可替代ajax获取/提交数据的技术,有些高级浏览器已经可以使用window.fecth使用了。相比于使用jQuery.ajax更轻量,而且它支持Promise,更加符合现在的编程习惯。
二、Fetch基本使用
npm install whatwg-fetch --save// fetch在各个浏览器低版本的情况下是不被支持的,由于fetch是基于promise实现的,所以在低版本浏览器中promise未必被原生支持npm install es6-promise --save // 开启react项目中的服务器代码进行测试
2-1 GET请求
#1. main.js import 'whatwg-fetch'import 'es6-promise'fetch('/api/homead',{ credentials:"include", /* fetch不管在同域还是在跨域的情况下,默认都不携带cookie的,所以那些需要权限验证的请求就无法正常获取到数据,这时候需要配置credentials项,有一下三个选项可添: omit: 默认值,忽略cookie的发送 same-origin: 表示cookie只能同域发送,不能跨域发送 include: 表示既可以同域发送,也可以跨域发送 */ }) .then(response => { //有三种方式解析获取到的数据: //1 json数据 用reponse.json()来解析 //2 xml格式文件 用response.text()来解析 //3 图片文件 用response.blob()来解析 return response.json(); }) .then((data)=>{ console.log(data); })#2.webpack.config.js 中配置代理开启跨域请求 devServer: { proxy: { '/api/*': { target: 'http://127.0.0.1:3001/', changeOrigin: true, secure: false } } }, //表示凡是以api开头的请求都会自动去请求http://127.0.0.1:3001/ 地址下的服务
2-2 POST请求
//post请求需要提交的数据 fetch('/api/submitComment', { method: 'post', //请求方式 credentials:"include", headers: { //post请求格式 'Content-Type': 'application/x-www-form-urlencoded' }, //post请求发送的数据需要是这样的 body: "name=zhangsan&content=宝宝不开心" }) .then(response => response.json()) .then(data=>{ console.log(data); }).catch(error => console.log('error is', error));
2-3 fetch请求的封装
import 'whatwg-fetch'import 'es6-promise'//导出get请求export function fetchget(url) { var result = fetch(url, { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*' } }); return result;}// 发送 post 请求export function fetchpost(url, paramsObj) { var result = fetch(url, { method: 'POST', credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', 'Content-Type': 'application/x-www-form-urlencoded' }, body: obj2params(paramsObj) }); return result;}// 将对象拼接成 key1=val1&key2=val2&key3=val3 的字符串形式function obj2params(obj) { var result = ''; var item; for (item in obj) { result += '&' + item + '=' + encodeURIComponent(obj[item]); } if (result) { result = result.slice(1); } return result;}