fetch 使用记录

fetch api出来不少年了 ,因为兼容性问题以前一直没在项目中用到,最近作的项目只需兼容IE9+,把fetch引入了进来。目前用起来感受挺好的,简洁。html

fetch 返回值是promise对象,对于不支持promise的须要引入promise-polyfill: https://www.npmjs.com/package/es6-promise-polyfill 。 对于不支持fetch的须要引入fetch-polyfill :https://github.com/github/fetchgit

因为fetch不支持jsonp, 若是须要使用jsonp, 能够引入fetch-jsonp :https://github.com/camsong/fetch-jsonp, 其使用方式和fetch基本同样。es6

//最简单的使用方式:fetch(url, [options]), 对于get请求,参数需添加到url后面
fetch(url).then((response) => response.json()).then((response) => { console.log(response)}) 

fetch请求提供了很是灵活的配置github

1. 直接在options配置web

options.method //GET, POST, PUT, DELETE, HEAD
options.headers = 
{
    // 'Access-Control-Allow-Origin': '*',
    // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //application/json
    // 'Content-Type': 'multipart/formdata; charset=UTF-8' //application/json
},
options.credentials=include //容许请求发送cookie
options.body = new FormData(form)  //post请求
options.body = JSON.stringify(params) //post请求

2. 使用 new Headers()建立请求头npm

let myHeaders = new Headers();

myHeaders.append('Content-Type', 'text/xml');

myHeaders.append('Custom-Header', 'CustomVal');

myHeaders.has('Content-Type');//true

myHeaders.get('Content-Type');//text/xml

myHeaders.set('Content-Type', 'application/json');

myHeaders.delete('Custom-Header');

//或直接以参数的形式建立

let myHeaders = new Headers({
    'Content-Type': 'application/json'
});

建立一个Request 对象来包装请求头:json

var myRequest = new Request(url,{
 headers:new Headers({
    
  })
});

fetch(myRequest).then((response)=>response.json)

 

能够发现fetch和Request参数基本一致,能够经过 Request() 和 Response() 的构造函数直接建立请求和响应,可是不建议这么作。他们应该被用于建立其余 API 的结果(mdn上说的)segmentfault

3. 响应api

Response 表明响应,fetch 的then 方法接受一个Response实例promise

response提升了不少属性和方法,https://developer.mozilla.org/zh-CN/docs/Web/API/Response

其中常常会用到response.json() /response.text() ,返回一个promise对象。

let fetchFn = function (opts) {
    let options = {
            url : '', // 路径
            method : 'GET', 
            params: {
                
            },
            headers : {
                 'Access-Control-Allow-Origin': '*',
                 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 
            },
            success(){},
            error(){} 
};
    options = extend(options, opts);
    let fetchParams = {
        method: options.method,
        headers: options.headers,
        credentials : 'include' //容许发送cookie 
    }
    if (options.method == 'GET'){
        options.url = toUrlParams(options.url, options.params); // 将参数拼接在url后面
    }else{
         fetchParams.body = JSON.stringify(options.params);
         if (options.form){
            fetchParams.body = new FormData(options.form)
        }
    }
    fetch(opts.url, fetchParams).then(response => response.json()).then(result => {
        if (result.code == 0){
            options.success(result);
        }else{
            options.error(result);
        }
    }).catch(e =>{
        console.log(' failed:', e)
    });
}
View Code

 

参考文档:

https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API

http://www.cnblogs.com/hsprout/p/5504053.html

http://web.jobbole.com/84924/

https://segmentfault.com/a/1190000003810652

相关文章
相关标签/搜索