wtfetch
A wrapper around the fetch API to simplify making HTTP requests. Each HTTP method has its own function that can be imported or required into wherever needed.
Installation
npm install --save wtfetch
Usage
// Import or require functions from library // Use the function to make HTTP request
Default Configurations
By default, each request will have the following configurations:
headers: 'Accept': 'application/json' 'Content-Type': 'application/json' credentials: 'same-origin' // enables cookies
Note that these can be overridden by passing the same key to the options of the request function.
;
Request Function Return Behavior
- Each successful request will return a promise chain with the json of the response body.
- Each unsuccessful request will throw an unhandled exception that must be handled outside of the library.
API
This library exposes 4 functions to make HTTP requests:
get
post
patch
deleteRequest
get(url [, options])
- Url should not include the query strings, instead query strings should be passed in as a
js object in the options with the key
data
- In the options, use the key
data
with a js object to send parameters to the server. Useful for search queries, filters, etc. Note that this supports nested objects - Additional option keys will be sent as is. Make sure the option provided is valid in this doc: https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters
Example
// with ES6 syntax // sends get request to www.example.com?q=hello+world// logs out the response or the error
post(url [, options])
- In the options, use the key
data
with a js object to send parameters to the server. - Additional option keys will be sent as is. Make sure the option provided is valid in this doc: https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters
Example
// with ES6 syntax
patch(url [, options])
- In the options, use the key
data
with a js object to send parameters to the server. - Additional option keys will be sent as is. Make sure the option provided is valid in this doc: https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters
Example
// with ES6 syntax
deleteRequest(url [, options])
- In the options, use the key
data
with a js object to send parameters to the server. - Additional option keys will be sent as is. Make sure the option provided is valid in this doc: https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch#Parameters
Example
// with ES6 syntax
Dependencies
whatwg-fetch
v2.0 forfetch
polyfill.
Testing
- Mocha as the test runner.
- Chai as the assertion library.
- Sinon to spy on stuff.
- fetch-mock for mocking HTTP requests.