fetch-pipe

利用promise改造的ajax请求 可以跨域请求 也可以xml请求

Installation

You can install with npm.

npm install fetch-pipe

npm地址 fetch-pipe

Usage

const fetchPipe=require('fetch-pipe');
fetchPipe({
url:'/users.jsonp', //Set type name, default is 'GET';
data:{key:1},
type:'post'
})
.then(function(response) {
return response.json()
}).then(function(json) {
//接收成功数据
console.log('parsed json', json)
}).catch(function(ex) {
//捕获异常
console.log('parsing failed', ex)
})

note:fetchPipe内的参数以对象的形式传进去,所传的参数规则同ajax一致

跨域请求

跨域请求一定要设定dataType:’jsonp’ ;
Set JSONP callback name, default is ‘callback’;
Set JSONP request timeout, default is 5000ms.

fetchPipe({
url:'/users.jsonp',
dataType:'jsonp',
data:{key:1},
timeout:3000,
jsonpCallback: 'custom_callback',
jsonpCallbackFunction: '<name of your callback function>'
})
.then(function(response) {
return response.json()
}).then(function(json) {
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})

非跨域请求

非跨域请求 是按照dataType不是jsonp来判断的 则按照XMLHttpRequest进行请求

fetchPipe({
url:'/xml.json',
data:'key=1&value=3'
})
.then(function(response) {
return response.json()
}).then(function(json) {
let result = JSON.parse(json) //非跨域请求接收到的数据 要JSON.parse转换一下
console.log('parsed json', json)
}).catch(function(ex) {
console.log('parsing failed', ex)
})

Caveats

You need to call .then(function(response) { return response.json(); }) in order
to keep consistent with Fetch API.

Browser Support

Chrome Firefox IE Opera Safari
Latest ✔ Latest ✔ 8+ ✔ Latest ✔ 6.1+ ✔

实践

最新的版本加入了Object.assign 的兼容性 目前在手机端浏览器未发现其他问题 亲证可靠
例如像iphone4版本过低,不支持promise的,未兼容

License

MIT

Acknowledgement

Thanks to eastlee

sunbaixin wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!