Simple, easy to use fetch wrapping module
npm install zoyi-simple-fetch
npm test
npm run build
// Require
var sf = require('zoyi-simple-fetch')
// Create instance
var client = new sf.Client()
// Set base url
client.setBaseUrl('http://base.url')
// Set base url depending on NODE_ENV
client.setBaseUrl({
staging: 'http://dev.base.url', // if NODE_ENV is 'staging'
production: 'http://base.url' // if NODE_ENV is 'production'
})
client.setDefaultHeader({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
client.setHeaderInterceptor((header) => {
// header is defaultHeader
header['X-Auth-Token'] = 'ABCD'
return header
})
// default value is '' (means no use)
client.credentials = ''
// Use cookies for same origin
client.credentials = 'same-origin'
// For CORS
client.credentials = 'include'
const query = { key: 'value' }
client.get('url', query)
const body = { key: 'value' }
client.post('url', body)
client.put('url', body)
const body = { key: 'value' }
client.postByUrlEncoding('url', body)
client.putByUrlEncoding('url', body)
client.delete('url')
client.get('url').then((body: JSON) => {
console.log(body)
})
client.get('url').then(() => {}).catch((err: Error) => {
console.error(err)
})
// Error type is below.
interface Error {
status: string; // status code
statusText: string; // status text
body: JSON; // json decoded response body
}
// Tested in Safari, Chrome, IE10, IE11, Edge
{
status: 0,
statusText: 'TypeError ~~'
}
- Abstract file upload and Support uploading progress