xhr-plus
v1.5.2
Published
xhr-plus
Downloads
43
Maintainers
Readme
xhr-plus
XMLHttpRequest plus. support jsonp, iframe upload, sub domain proxy and more...
Example
http://localhost:8000/examples/
install
Usage
import io from 'xhr-plus';
io({
url: '//x.com',
method: 'get',
data: {
param: 'v',
},
success(data) {
},
error(e) {
},
}).then((data) => {
}).catch(e => {
});
Promise support, place the following code inside your html head
<script>
if(!window.Promise) {
document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
}
</script>
API
var req = io(config);
// req.abort();
config
methods
abort():void
abort current request
then(data): Promise
use data in promise
catch(e:{message, status, xhr}): Promise
catch error in promise
always(data|e)
always process in promise
static methods
ajaxSetUp(config)
set the default config for all requests
interceptors
You can intercept requests or responses like axios.
// Add a request interceptor
io.interceptors.request.use((config) => {
// Do something before request is sent
return config;
});
// Add a response interceptor
io.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
And what's fun is you can turn a response into error
io.interceptors.response.use(function (response) {
if(response.notLogin) {
const error = new Error('not login');
error.isSystemError = true;
return Promise.reject(error);
}
});
If you may need to remove an interceptor later you can.
var myInterceptor = io.interceptors.request.use(function () {/*...*/});
io.interceptors.request.eject(myInterceptor);
Test Case
npm test
npm run chrome-test
Coverage
npm run coverage
open coverage/ dir
License
xhr-plus is released under the MIT license.