fetch-s
Fetch-based HTTP requests
Features
- Supports the Promise API
- Supports
Timeout
- Transform request data
- Analysis response data
- Interceptor
- Custom instance defaults
- Supports
JSONP
Installing
Using npm:
$ npm install fetch-s
Using CDN:
<script src="https://unpkg.com/fetch-s/dist/fetchs.min.js" />
Example
Performing a GET
request
// Make a request for a user with a given IDfetchs ; // Optionally the request above could also be done asfetchs ;
Performing a POST
request
fetchs ;
Performing a JSONP
request
// Make a request for a user with a given IDfetchs ; // Optionally the request above could also be done asfetchs ;
Request Config
These are the available config options for making requests. Only the url
is required. Requests will default to GET
if method
is not specified.
// request type method: 'GET' // default //`url` is the request path //If u is a relative path, it will be combined with `origin` to form a complete path url:'' //`data` are the request parameters data: id: 1 // `responseType` indicates the type of data that the server will respond with // options are 'arrayBuffer', 'blob', 'formData', 'text', 'json' dataType: 'json' //`origin` is the request baseURL origin: '' //`mode` is the request mode ("same-origin"、"no-cors"、"cors") mode: 'cors' // default // Sending a request with credentials included //To cause browsers to send a request with credentials included, even for a cross-origin call, add credentials: 'include' to the init object you pass to the fetch() method. //If you only want to send credentials if the request URL is on the same origin as the calling script, add credentials: 'same-origin'. //To instead ensure browsers don’t include credentials in the request, use credentials: 'omit'. credentials: 'include'// default //`timeout` specifies the number of milliseconds before the request times out timeout: 30000 // default // `headers` the headers that the server request with headers: {}
Response Schema
The response for a request contains the following information.
// `data` is the response that was provided by the server data: {} // `config` is the config that was provided to `fetch-s` for the request config: {} // `status` is the HTTP status code from the server response status: 200 // `statusText` is the HTTP status message from the server response statusText: 'OK' //Contains a boolean stating whether the response was successful (status in the range 200-299) or not. ok: true //`redirect` is to identify if the request has redirects redirected: false // `headers` the headers that the server responded with headers: {} // `body` the body that the server responded with body: ReadableStream
Interceptors
You can intercept requests or responses before they are handled by then
or catch
.
// Add a request interceptorfetchsinterceptorsrequest; // Add a response interceptorfetchsinterceptorsresponse;
Custom instance defaults
// Set config defaults when creating the instancevar instance = fetchs; //and use itinstance ;