1.2.3 • Published 5 years ago
http-fetch-ts v1.2.3
http-fetch-ts
Download/install
yarn add http-fetch-ts --save
or
npm install http-fetch-ts --saveBasic usage
httpFetch("http://website.com")
.then((res) => console.log(res))
.catch(error => console.log(error));You can use import httpFetch the ES6 way if you wish to:
import httpFetch from "http-fetch-ts";
httpFetch("http://website.com")
.then((res) => console.log(res))
.catch(error => console.log(error));response and Error objects
httpFetch changes the res and error objects. In httpFetch, response and error objects both include these five properties:
headers: response headersbody: response bodystatus: response statusstatusText: response status textresponse: original response from Fetch
httpFetch("http://website.com")
.then((res) => {
const headers = res.headers;
const body = res.body;
})
.catch((error) => {
const headers = error.headers;
const body = error.body;
const status = error.status;
});GET requests
To send a GET request, enter the endpoint as the first argument.
// With httpFetch
httpFetch("http://website.com");
// With fetch api
fetch("http://website.com");httpFetch formats and encodes query parameters for you if you provide a params option.
httpFetch('http://website.com', {
params: {
param1: 'value1',
param2: 'to encode'
}
})
// With fetch API
fetch('http://website.com?param1=value1¶m2=to%20encode')POST requests
Set method to POST to send a POST request. httpFetch will set Content-Type will be set to application/json for you. It will also convert your body to a JSON string automatically.
// with httpFetch
httpFetch("http://website.com", {
method: "POST",
body: { key: "value" }
});
// Resultant fetch api
fetch("http://website.com", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: { key: "value" }
});
// Setting other content type
httpFetch("http://website.com", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" }
});Other Content-Types
You may choose to overwrite Content-Type yourself. To do so, pass headers and Content-Type property.
fetch("http://website.com", {
method: "POST",
headers: { "Content-Type": "Another Content Type" },
body: { key: "value" )
});Authentication/Authorization
httpFetch adds Authorization headers for you if you include an auth property.
// Resultant fetch api
fetch("http://website.com", {
headers: { Authorization }
});Shorhand methods
Supported shorthand methods include:
getpostputputchdelete
httpFetch.post('http://website.com')
//as
httpFetch('http://website.com', { method: 'POST' })