Wraps Fetch API (experimental)
- Fail: check everything
- Cancellation: cancel anything
- Encryption: encrypt everything (FF only)
- Retry: restart anything
- Download: download anything
- Upload: upload anything
- Streams: stream something
- Mix: mix everything
ES5 script (classic)
<!-- CDN (stable) -->
<script src="https://cdn.jsdelivr.net/npm/http-fetch-json@2/httpFetch.js"></script>
<!-- GIT (lastest) -->
<script src="http://raw.githack.com/determin1st/httpFetch/master/httpFetch.js"></script>
ES6 module
// TODO
get the code
# GIT (lastest)
git clone https://github.com/determin1st/httpFetch
# NPM (stable)
npm i http-fetch-json
-
options
- an object with:base
name type default description url
string reference to the local or remote web resource (auto-prefixed with baseUrl
if doesn't contain sheme)data
any content to be sent as the request body
native fetch
name type default description method
string HTTP request method (detected automatically) mode
string cors
fetch mode credentials
string same-origin
to automatically send cookies cache
string default
the cache mode to use for the request redirect
string follow
the redirect mode to use. manual
is screwed by spec authorreferrer
string referrer url referrerPolicy
string the referrer policy to use integrity
string the subresource integrity value of the request keepalive
boolean false
allows the request to outlive the page
advanced
name type default description status200
boolean true
to consider only HTTP STATUS 200 OK notNull
boolean false
to consider only nonempty HTTP response body and not JSON NULL fullHouse
boolean false
to include everything, request and response, data and headers promiseReject
boolean false
promise will reject with Error timeout
integer 20
request will abort in the given delay in seconds redirectCount
integer 5
manual redirects limit (non-functional, because spec author screwd it) aborter
aborter to cancel request with given controller headers
object {..}
request headers parseResponse
string data
data
is to parse all the content to proper content type,stream
forFetchStream
, otherwise, raw response
-
callback(ok, res)
- optional result handler functionok
- boolean flag, indicates the result typeres
- response result data or FetchError
Promise
(no callback) or AbortController
(callback)
async/await
var res = await httpFetch('/resource');
if (res instanceof Error)
{
// FetchError
}
else if (!res)
{
// JSON falsy values
}
else
{
// success
}
promise
httpFetch('/resource')
.then(function(res) {
if (res instanceof Error)
{
// FetchError
}
else if (!res)
{
// JSON falsy values
}
else
{
// success
}
});
callback
httpFetch('/resource', function(ok, res) {
if (ok && res)
{
// success
}
else if (!res)
{
// JSON falsy values
}
else
{
// FetchError
}
});
custom instance
var oFetch = httpFetch.create({
notNull: true
});
async/await
var res = await oFetch('/resource');
if (res instanceof Error)
{
// FetchError
}
else
{
// success
}
promise
oFetch('/resource')
.then(function(res) {
if (res instanceof Error)
{
// FetchError
}
else
{
// success
}
});
callback
oFetch('resource', function(ok, res) {
if (ok)
{
// success
}
else
{
// FetchError
}
});
custom instance
var pFetch = httpFetch.create({
promiseReject: true
});
async/await
try
{
var res = await pFetch('/resource');
if (res)
{
// success
}
else
{
// JSON falsy values
}
}
catch (err)
{
// FetchError
}
promise
oFetch('/resource')
.then(function(res) {
if (res)
{
// success
}
else
{
// JSON falsy values
}
})
.catch(function(err)
{
// FetchError
});
custom instance
var pFetch = httpFetch.create({
notNull: true,
promiseReject: true
});
async/await
try
{
var res = await pFetch('/resource');// success
}
catch (err)
{
// FetchError
}
promise
oFetch('/resource')
.then(function(res) {
// success
})
.catch(function(err)
{
// FetchError
});
- JSON
application/json
- String
text/*
- ArrayBuffer
application/octet-stream
- ...
- Blob
image/*
audio/*
video/*
- FormData
multipart/form-data
- null
application/json
whenJSON NULL
application/octet-stream
when notbyteLength
image/*
,audio/*
,video/*
when notsize
- when HTTP response body is empty
- FetchStream
- when
parseResponse
isstream
- when
- FetchError
- when fetch() fails
- when unsuccessful HTTP status code
- when not HTTP STATUS 200 OK and
status200
- when
JSON NULL
andnotNull
- when HTTP response body is empty and
notNull
- ...
error categories
if (res instanceof Error)
{
switch (res.id)
{
case 0:
///
// connection problems:
// - connection timed out
// - wrong CORS headers
// - unsuccessful HTTP STATUSes (not in 200-299 range)
// - readable stream failed
// - etc
///
console.log(res.message); // error details
console.log(res.response); // request + response data, full house
break;
case 1:
///
// something's wrong with the response data:
// - empty response
// - incorrect content type
// - etc
///
break;
case 2:
///
// security compromised
///
break;
case 3:
///
// incorrect API usage
// - wrong syntax used
// - something's wrong with the request data
// - internal bug
///
break;
case 4:
///
// aborted programmatically:
// - canceled parsing, before the request was made
// - canceled fetching, before the response arrived
// - canceled parsing, after the response arrived
// - stream canceled
///
break;
case 5:
///
// unclassified
///
break;
}
}
httpFetch.create
config
- an object with instance options
Creates a new instance of of httpFetch
var a = httpFetch.create();
var b = a.create();
if ((a instanceof httpFetch) &&
(b instanceof httpFetch))
{
// true!
}
httpFetch.form
httpFetch operates with JSON content by default.
This shortcut method allows to send a POST
request
with body conforming to one of the form enctypes:
application/x-www-form-urlencoded
: query stringmultipart/form-data
:FormData
with attachmentstext/plain
: plaintext The proper content type will be detected automatically.
Same as httpFetch
// CLIENT (JS)
// let's send a plain content without files,
// there is no need in FormData format, so
// it will be automaticly detected as
// x-www-form-urlencoded:
res = httpFetch.form(url, {
param1: 1,
param2: 2,
param3: 3
});
# SERVER (PHP)
# get parameters and calculate their sum:
$sum = $_POST['param1'] + $_POST['param2'] + $_POST['param3'];
# respond with JSON
echo json_encode($sum);
# and quit
exit;
// CLIENT (JS)
// wait for the response and display it:
console.log(await res);// 6
// CLIENT (JS)
// let's send another request with file attached,
// the body will be sent as
// multipart/form-data:
res = await httpFetch.form(url, {
param1: 1,
param2: 2,
param3: 3,
fileInput: document.querySelector('input[type="file"]')
});
// SERVER's $_FILES will be populated with uploaded file,
// but the response/result will be the same:
console.log(res);// 6
overview
What exactly is the REST API? In a nutshell, it's only a collection of endpoints:
Endpoints are important aspects of interacting with server-side web APIs, as they specify where resources lie that can be accessed by third party software. Usually the access is via a URI to which HTTP requests are posted, and from which the response is thus expected.
The original definition of the REST does not restrict or explicitly specify certain HTTP methods to use with, there is no CRUD in there. Check the link and try to find it, if you doubt.
Still, some dumb dumbies are unable to differentiate the origin and the mutatated forms of the term, but thats not the reason why KISS word is used.
The KISS (Keep It Simple Stupid) is how the REST is implemented.
What is AJAX then? Well, thats also an implementation of the REST (or a subset). It is bound to the JavaScript, XML and XMLHttpRequest. Generally, you say that jQuery, axios, superagent or other lib is AJAX if it utilizes XMLHttpRequest api. ...
What about RPC? ...
how
// instead of GET method, you may POST:
res = await httpFetch(url, {}); // EMPTY OBJECT
res = await httpFetch(url, undefined);// EMPTY BODY
res = await httpFetch(url, null); // JSON NULL
// it may easily expand to
// into list filters:
res = await httpFetch(url, {
categories: ['one', 'two'],
flag: true
});
// or item extras:
res = await httpFetch(url, {
fullDescription: true,
ownerInfo: true
});
// OTHERWISE,
// parametrized GET will swamp into:
res = await httpFetch(url+'?flags=123&names=one,two&isPulluted=true');
// DO NOT use multiple/mixed notations:
res = await httpFetch(url+'?more=params', params);
res = await httpFetch(url+'/more/params', params);
// DO unified:
res = await httpFetch(url, Object.assign(params, {more: "params"}));
// by default,
// any HTTP status, except 200 is a FetchError:
if (res instanceof Error) {
console.log(res.status);
}
else {
console.log(res.status);// 200
}
https://javascript.info/fetch-api
https://tom.preston-werner.com/2010/08/23/readme-driven-development.html
https://code.tutsplus.com/tutorials/why-youre-a-bad-php-programmer--net-18384
<style type="text/css"> summary {font-size:1.2em;font-weight:bold;color:skyblue;} </style>