
fetch.io
Extends the whatwg fetch
- fetch spec api,
makes it easier to use. Both node & browser supported.
npm install fetch.io
import Fetch from 'fetch.io'
APIs
-
.config() - set options
-
.set() - set http header
-
.type() - set content type
-
.send() - send body data
-
.query() - set query string
-
.append() - append form data
-
.text() - convert response body to string
-
.json(strict = true) - convert response body to object
(strict JSON mode default)
Options
- beforeRequest -
Function
, a pre-request hook function, returning false
will cancel the request - afterResponse -
Function
, a post-response hook function - afterJSON -
Function
, add a handler for .json()
, to check the response data - prefix -
String
, url prefix - Other whatwg-fetch options
Usage
const request = new Fetch({
prefix: 'http://example.com/api/v1'
})
{
prefix: '',
mode: 'cors',
cache: 'no-cache',
credentials: 'include'
}
request
.get(path)
.config({
credentials: 'omit'
})
.query({
type: 1
})
.query({
name: 'hello'
})
.then(res => {
})
.catch(err => {
})
request
.get(path)
.json()
.then(body => {
})
.catch(err => {
})
request
.get(path)
.text()
.then(body => {
})
.catch(err => {
})
request
.post(path)
.send({
type: 1
})
.send({
name: 'hello'
})
.then(res => {
})
.catch(err => {
})
request
.post(path)
.send('type=1')
.send('name=hello')
.then(res => {
})
.catch(err => {
})
request
.post(path)
.type('form')
.send({
type: 1,
name: 'hello'
})
.then(res => {
})
.catch(err => {
})
request
.post(path)
.set({
'content-type': 'application/json'
})
.send({
name: 'hello'
})
.then(res => {
})
.catch(err => {
})
- send form (multipart) (upload file)
request
.post(path)
.append('filename', 'user.png')
.append('file': document.querySelector('input[type="file"]')files[0])
.append({reason: 'set user avatar'})
.then(res => {
})
.catch(err => {
})
License
MIT