js-http-fetch
Fetch-based http request plugin, just fetch, no XMLHttpRequest.
Install
Use npm:
$ npm i js-http-fetch -S
Use yarn:
yarn add js-http-fetch
Use unpkg CDN:
<script src="https://unpkg.com/js-http-fetch/lib/js-http-fetch.min.js"></script>
Examples
First, import or require or link the module.
Use es6 module:
import HttpFetch from 'js-http-fetch';
HttpFetch('/url').then(res => console.log(res));
Use commonJs:
const HttpFetch = require('js-http-fetch');
HttpFetch('/url').then(res => console.log(res));
Use link:
<script src="https://unpkg.com/js-http-fetch/lib/js-http-fetch.min.js"></script>
<script>
window.HttpFetch('/url').then(res => console.log(res));
</script>
Create Instance
HttpFetch.create([config])
You can create an instance of HttpFetch
, and the instance will inherit the config of HttpFetch
and the request methods from Fetch
. The created instance is
no different from the use of HttpFetch
except that there is no create
method.
const base = 'http://someurl';
HttpFetch.config.base = base;
const http = HttpFetch.create();
console.log(http.config.base === base);
HttpFetch.config.base = 'http://oldurl';
HttpFetch.config.timeout = 5000;
const http = HttpFetch.create({
base: 'http://newurl',
timeout: 10000
});
console.log(http.config.base === 'http://newurl' && http.config.timeout === 10000);
See all the configs.
Request Methods
All requests return Promise, this may cause some compatibility issues.
HttpFetch('/', {data: {id: 1}, params: {title: 'tom'}});
HttpFetch({
url: '/',
method: 'post',
data: {id: 1},
params: {
title: 'tom',
},
headers: {}
});
HttpFetch.get('/');
HttpFetch.get('http://api', {id: 5});
HttpFetch.get('/', {id: 5}, {timeout: 3000});
HttpFetch.post('/');
HttpFetch.post('/', {id: 5});
HttpFetch.post('/', null, {timeout: 3000});
HttpFetch.delete('/', {}, {responseType: 'json'});
HttpFetch.patch('/', {}, {});
HttpFetch.put('/', {}, {});
HttpFetch.options('/', {}, {});
HttpFetch.head('/', {}, {});
Config(HttpFetch.config)
set config
Object.assign(HttpFetch.config, );
url
The requested url
, if the base
is configured and the url
is not absolute, the base
and url
will be concatenated as the complete url
when requesting.
base
The basic url
of the request, which will be spliced with the url
as the complete url
when sending the request.
data
If data
is one of Record<string, any> | Array<any> | number | boolean
, will be converted to a json string. And if Content-Type
is not set, will be automatically set to application/json
. After
the data
is processed, it will be passed into fetch
as the body
, that is, the request body.
params
The params
will be serialized into query string format and spliced into url
, refer to get
request.
HttpFetch({url: 'http://api', params: ['5', '7']});
HttpFetch({url: 'http://api', params: {a: '3', b: '6'}});
timeout
Set the timeout time of the request, if the request time is longer than this time, the request will be interrupted. If timeout
is 0 or not set, the request will not be aborted.
method
The way to send the request, when the request is finally sent, the method
will be converted to uppercase.
controller
The controller
used to abort the request, if you need to manually abort the request, please pass controller
instead of fetch
's signal
, because the abort request of timeout
uses the
same controller
. If multiple requests use the same controller
, be aware of the impact of manual abort requests on other requests.
responseType
Specifies the type of response data. If it is not set, it will try to parse it as json
by default. If the parsing fails, it will be parsed as text
, read more. If it is stream
, the response will not be processed, instead, directly return
the ReadableStream returned byfetch
.
Set request headers. For typescript, headers preset key Content-Type
.
onDownloadProgress
Hook to get download progress.
Abort Request
const controller = new AbortController();
HttpFetch.post('/', {}, {controller});
controller.abort();
Interceptors
request interceptors
You can pass in 2 function
, the first (resolver
) handles a successful Promise
, the second (rejecter
) handles a failed Promise
. You can directly return a config
object or a Promise
. You
can also use multiple interceptors
, they will execute in sequence (if Promise
, it will after resolve
or reject
).
HttpFetch.interceptors.request.use(config => {
config.headers = {token: 'my-token'}
console.log('first')
return config;
}, reason => {
console.log(reason);
return Promise.reject(reason);
});
HttpFetch.interceptors.request.use(config => {
console.log('second')
return new Promise(resolve => setTimeout(() => resolve(config), 1000));
});
response interceptors
Like request interceptors
, 2 function
can also be passed in, but the resolver has 3 parameters.
HttpFetch.interceptors.response.use((data, response, config) => {
return {data, response, config};
}, reason => {
console.log(reason);
return Promise.reject(reason);
});
HttpFetch.interceptors.response.use(data => {
console.log(data);
return new Promise(resolve => setTimeout(() => resolve(data), 500));
});
TypeScript
For the plugin, it doesn't know what type of data
is returned, you need to specify it yourself :
import HttpFetch from "js-http-fetch";
import {HttpFetchConfig} from "js-http-fetch/types/types";
interface FetchResponse {
data: Array<{ id: number, title: string }>
response: Response
config: HttpFetchConfig
}
HttpFetch.interceptors.response.use((data: any, response: Response, config: HttpFetchConfig) => ({data, response, config}));
HttpFetch.post<FetchResponse>('/').then(res => {
res.data.forEach(({id, title}) => {
});
});
Note
The use design draws on axios, for more convenient use.