fetch使用整理

浏览器支持情况

fetch是相对较新的技术,当然就会存在浏览器兼容性的问题,当前各个浏览器低版本的情况下都是不被支持的,因此为了在所有主流浏览器中使用fetch 需要考虑 fetch 的 polyfill 了

  
require('es6-promise').polyfill();
require('isomorphic-fetch');
  

引入这两个文件,就可以支持主流浏览器了

API

  
  fetch(url,{ // url: 请求地址
    method: "GET", // 请求的方法POST/GET等
    headers : { // 请求头(可以是Headers对象,也可是JSON对象)
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    },
    body: , // 请求发送的数据 blob、BufferSource、FormData、URLSearchParams(get或head方法中不能包含body)
    cache : 'default', // 是否缓存这个请求
    credentials : 'same-origin', //要不要携带 cookie 默认不携带 omit、same-origin 或者 include
    mode : "",
    /*
        mode,给请求定义一个模式确保请求有效
        same-origin:只在请求同域中资源时成功,其他请求将被拒绝(同源策略)
        cors : 允许请求同域及返回CORS响应头的域中的资源,通常用作跨域请求来从第三方提供的API获取数据
        cors-with-forced-preflight:在发出实际请求前执行preflight检查
        no-cors : 目前不起作用(默认)
*/</span>

}).then(resp => {
/*
Response 实现了 Body, 可以使用 Body 的 属性和方法:

    resp.type // 包含Response的类型 (例如, basic, cors).

    resp.url // 包含Response的URL.

    resp.status // 状态码

    resp.ok // 表示 Response 的成功还是失败

    resp.headers // 包含此Response所关联的 Headers 对象 可以使用

    resp.clone() // 创建一个Response对象的克隆

    resp.arrayBuffer() // 返回一个被解析为 ArrayBuffer 格式的promise对象

    resp.blob() // 返回一个被解析为 Blob 格式的promise对象

    resp.formData() // 返回一个被解析为 FormData 格式的promise对象

    resp.json() // 返回一个被解析为 Json 格式的promise对象

    resp.text() // 返回一个被解析为 Text 格式的promise对象
*/</span>
<span class="hljs-keyword">if</span>(resp.status === <span class="hljs-number">200</span>) <span class="hljs-keyword">return</span> resp.json();
<span class="hljs-comment">// 注: 这里的 resp.json() 返回值不是 js对象,通过 then 后才会得到 js 对象</span>
<span class="hljs-keyword">throw</span> New <span class="hljs-built_in">Error</span> (<span class="hljs-string">'false of json'</span>);

}).then(json => {
console.log(json);
}).catch(error => {
consolr.log(error);
})

常用情况

请求 json

  
  fetch('http://xxx/xxx.json').then(res => {
    return res.json();
}).then(res => {
    console.log(res);
})

请求文本

  
  fetch('/xxx/page').then(res => {
    return res.text();
}).then(res => {
    console.log(res);
})

发送普通 json 数据

  
  fetch('/xxx', {
    method: 'post',
    body: JSON.stringify({
        username: '',
        password: ''
    })
});

发送form 表单数据

  
  var form = document.querySelector('form');
fetch('/xxx', {
    method: 'post',
    body: new FormData(form)
});

获取图片

URL.createObjectURL()

  
  fetch('/xxx').then(res => {
    return res.blob();
}).then(res => {
    document.querySelector('img').src = URL.createObjectURL(imageBlob);
})

上传

  
  var file = document.querySelector('.file')
var data = new FormData()
data.append('file', file.files[0])
fetch('/xxx', {
  method: 'POST',
  body: data
})

封装

  
  require('es6-promise').polyfill();
require('isomorphic-fetch');

export default function request(method, url, body) {
method = method.toUpperCase();
if (method === ‘GET’) {
body = undefined;
} else {
body = body && JSON.stringify(body);
}

<span class="hljs-keyword">return</span> fetch(url, {
    method,
    headers: {
        <span class="hljs-string">'Content-Type'</span>: <span class="hljs-string">'application/json'</span>,
        <span class="hljs-string">'Accept'</span>: <span class="hljs-string">'application/json'</span>
    },
    body
}).then((res) =&gt; {
    <span class="hljs-keyword">if</span> (res.status &gt;= <span class="hljs-number">200</span> &amp;&amp; res.status &lt; <span class="hljs-number">300</span>) {
        <span class="hljs-keyword">return</span> res;
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> Promise.reject(<span class="hljs-string">'请求失败!'</span>);
    }
})

}

export const get = path => request(‘GET’, path);
export const post = (path, body) => request(‘POST’, path, body);
export const put = (path, body) => request(‘PUT’, path, body);
export const del = (path, body) => request(‘DELETE’, path, body);

参考

Fetch API 初探 Fetch API XHR or Fetch API ?

作者:mjzhang1993
来源:CSDN
原文:https://blog.csdn.net/mjzhang1993/article/details/72833095
版权声明:本文为博主原创文章,转载请附上博文链接!