脚本宝典收集整理的这篇文章主要介绍了前端临床手扎——简单易用的fetch,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
如题,es6 新增的fetch
真的简单易用,感觉现在这一个支持完全可行。
虽然兼容性问题还是存在,但是打上polyfill
后就基本解决了。
browser Support
Chrome
Firefox
Safari 6.1+
internet Explorer 10+
使用
简单使用
这里说明一下,fetch
必须配合PRomise
一起使用,这会得到更佳效果。
# 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'
参数,如:
# 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);
你可能还需要...
想使用起来更舒心,你还得引用以下这两个包解决兼容:
具体使用例子:
# 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)
}
}
以上是脚本宝典为你收集整理的前端临床手扎——简单易用的fetch全部内容,希望文章能够帮你解决前端临床手扎——简单易用的fetch所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。