如题,es6 新增的fetch
真的简单易用,感觉现在这一个支持完全可行。
虽然兼容性问题还是存在,但是打上polyfill
后就基本解决了。
1 2 3 4 5 6 Browser Support Chrome Firefox Safari 6.1+ Internet Explorer 10+
来自:github / fetch
使用 简单使用 这里说明一下,fetch
必须配合promise
一起使用,这会得到更佳效果。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 # get fetch('/api/user/1', {method: 'GET'}).then(res => res.json).then(console.log).catch(console.error); # console.log ###### # {id: 1, username: 'Packy', email: 'packy@uxfeel.com'} # post var formData = new FormData(); formData.append('username', 'cathy'); formData.append('email', 'cathy@uxfeel.com'); fetch('/api/user', {method: 'POST', body: formData}).then(res => res.json).then(console.log).catch(console.error); # console.log ###### # {code: '0', msg: '', data:{}}
跨域 跨域问题并不难只需加上 mode:'cors'
参数,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 # cross post var formData = new FormData(); formData.append('username', 'cathy'); formData.append('email', 'cathy@uxfeel.com'); fetch( 'http://192.168.1.120/api/user', { method: 'POST', body: formData, // 设为跨域请求 mode:'cors' } ).then(res => res.json).then(console.log).catch(console.error);
想详细了解,请记住CORS
关键词并看这里
你可能还需要… 想使用起来更舒心,你还得引用以下这两个包解决兼容:
具体使用例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 # api.js require('es6-promise').polyfill(); require('fetch'); // 此判断在某些浏览器并不能正常检查,导致URLSearchParams不可用,如果你知道具体问题联系以下博主 //if ('searchParams' in HTMLAnchorElement.prototype) { var URLSearchParams = require('url-search-params'); //} function handle(response){ return new Promise(function(resolve, reject){ if(response.status === 200){ resolve(response.json()) }else{ var message = defaults.serverError[response.status]; var e = new Error(message || '未知请求错误!'); e.response = response; reject(e); } }); } module.exports = { // 登录 login: function(data){ var url = '/user/login'; var formData = new FormData(); Object.keys(data).map(function(attr){ formData.append(attr, data[attr]); }) return fetch(url, { method: 'POST', body: formData, }).then(handle).catch(handle); }, // 发送手机验证短信 sendCode: function(data){ var url = '/user/sendCode'; var params = new URLSearchParams(''); Object.keys(data).map(function(attr){ params.append(attr, data[attr]); }) url+='?'+params.toString(); return fetch(url, { method: 'GET', }).then(handle).catch(handle) } }
v1.5.2