A lightweight Promise based HTTP client, using Fetch API.
- Uses Fetch API
- Works on both old and new browsers and on Node.js
- Supports the Promise API
- Transform request and response data
- Automatic transforms for JSON data
npm i --save fitch
With ES2015 or TypeScript:
import fitch from 'fitch'
CommonJS:
const fitch = require('fitch')
CDN:
unpkg
<script src="https://unpkg.com/fitch/dist/index.umd.min.js"></script>
jsDelivr
<script src="https://cdn.jsdelivr.net/g/fitch.js"></script>
fitch.get(apiUrl)
.then(response => console.log(response))
/* Response:
{
data: { foo: 'bar' },
status: 200,
statusText: 'Ok',
headers: { Content-Type: application/json },
}
*/
fitch.get(apiUrl)
.then(response => console.log(response))
const req = {body: {name: 'Happy cat'}}
fitch.post(apiUrl, req)
.then(response => console.log(response))
const req = {body: {name: 'Happy cat'}}
fitch.put(apiUrl, req)
.then(response => console.log(response))
const req = {body: {name: 'Happy cat'}}
fitch.patch(apiUrl, req)
.then(response => console.log(response))
fitch.del(apiUrl)
.then(response => console.log(response))
const config = {
cache: 'no-store',
headers: { 'Content-Type': 'application/json' },
mode: 'no-cors',
params: { // transform to '?test1=test-1&test2=test-2'
test1: 'test-1',
test2: 'test-2',
},
raw: true, // return the raw output of fetch()
redirect: 'follow',
}
fitch.get(apiUrl, config)
.then(response => console.log(response))
See more about fetch configuration at: Fetch API.
Helper function for dealing with concurrent requests.
const reqDogs = fitch.get('/dogs')
const reqCats = fitch.get('/cats')
function doSomething([ responseDogs, responseCats ]) {
console.log('Dogs\t>>>', responseDogs)
console.log('Cats\t>>>', responseCats)
}
fitch.all([ reqDogs, reqCats ])
.then(doSomething)
const fetchWrapper = fitch.init({
config: { raw: true },
interceptor: response => response.json(),
})
fetchWrapper.get(baseUrl).then(data =>
console.log('GET with interceptor\t>>>', data)
)
- Chrome
- Firefox
- Edge
- Safari 6.1+
- Internet Explorer 10+
Note: modern browsers such as Chrome, Firefox, and Microsoft Edge contain native implementations of window.fetch, so the polyfill doesn't have any affect on those browsers. See more at window.fetch polyfill.
Read the Code of conduct.
First yout need to fork this repository. Then:
yarn # install local dependencies
yarn start # run local server
yarn watch:test # watch files inside src/ and tests/
yarn build # run examples
yarn examples # run examples
Note: Your code must be tested and pass in linter check.
You can verify your code with ESLint, using npm run lint
.
Copyright © Bárbara Schoen