Security News
The Dark Side of Open Source
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
http-fetch-json
Advanced tools
Readme
Individual fetch API wrapper for the browser (experimental, reactionary)
The thing, is pretty fast as it doesnt try to connect worlds, but rather lives in it's own native environment (the browser). So it will catch up with you faster than you may think.
HTTP request and response routine is super boring but standard procedure for all kinds of stuff.
For the UI and interactions, the browser's api is used, so it's almost the same thing you do at the server side.
While some folks having trouble with so called "native" apis, the best of us are using wrappers (self-made or libs - doesnt matter).
This thing, is kind of a wrapper, but packed with extra options and routes which may or may not happen with you during the HTTP request/response exchange.
It's more advanced that any other tool (which try to keep pace with the NODE's world) as it uses (currently) experimental features of the browser (like fetch, streams, encryption). It may be more aggressive at your environment - only modern syntax, only modern apis (the approach may be same). As far as this time point vanishes in the past, the previous statement becomes falsy.
So, the attempt of escaping the doom is futile: face it one-to-one with the Spider Mastermind.
inject into HTML:
# from CDN (stable):
<script src="https://cdn.jsdelivr.net/npm/http-fetch-json@2/httpFetch.js"></script>
# from GIT (lastest)
<script src="http://raw.githack.com/determin1st/httpFetch/master/httpFetch.js"></script>
get the code:
# with GIT (lastest)
git clone https://github.com/determin1st/httpFetch
# with NPM (stable)
npm i http-fetch-json
httpFetch(options[, callback(ok, res)])
httpFetch(url[, data[, callback(ok, res)]])
httpFetch(url[, callback(ok, res)])
options
- object with: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 |
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 author |
referrer | 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 |
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 (functional only with http status 300) |
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 for FetchStream , otherwise, raw response |
callback
- optional result handler functionok
- boolean flag, indicates the successful resultres
- response result, either success or FetchErrorPromise
(no callback) or AbortController
(callback)
var res = await httpFetch('/resource');
if (res instanceof Error)
{
// FetchError
}
else if (!res)
{
// JSON falsy values
}
else
{
// success
}
httpFetch('/resource')
.then(function(res) {
if (res instanceof Error)
{
// FetchError
}
else if (!res)
{
// JSON falsy values
}
else
{
// success
}
});
httpFetch('/resource', function(ok, res) {
if (ok && res)
{
// success
}
else if (!res)
{
// JSON falsy values
}
else
{
// FetchError
}
});
notNull
var oFetch = httpFetch.create({
notNull: true
});
var res = await oFetch('/resource');
if (res instanceof Error)
{
// FetchError
}
else
{
// success
}
oFetch('/resource')
.then(function(res) {
if (res instanceof Error)
{
// FetchError
}
else
{
// success
}
});
oFetch('resource', function(ok, res) {
if (ok)
{
// success
}
else
{
// FetchError
}
});
promiseReject
var pFetch = httpFetch.create({
promiseReject: true
});
try
{
var res = await pFetch('/resource');
if (res)
{
// success
}
else
{
// JSON falsy values
}
}
catch (err)
{
// FetchError
}
oFetch('/resource')
.then(function(res) {
if (res)
{
// success
}
else
{
// JSON falsy values
}
})
.catch(function(err)
{
// FetchError
});
promiseReject
and notNull
var pFetch = httpFetch.create({
notNull: true,
promiseReject: true
});
try
{
var res = await pFetch('/resource');// success
}
catch (err)
{
// FetchError
}
oFetch('/resource')
.then(function(res) {
// success
})
.catch(function(err)
{
// FetchError
});
application/json
text/*
application/octet-stream
image/*
audio/*
video/*
multipart/form-data
application/json
when JSON NULL
application/octet-stream
when not byteLength
image/*
, audio/*
, video/*
when not size
parseResponse
is stream
status200
JSON NULL
and notNull
notNull
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)
config
- object with optionsCreates a new instance of of httpFetch
var a = httpFetch.create();
var b = a.create();
if ((a instanceof httpFetch) &&
(b instanceof httpFetch))
{
// true!
}
httpFetch.cancel()
Cancels all running fetches of the instance
httpFetch.form(url, data[, callback(ok, res)])
httpFetch.form(options[, callback(ok, res)])
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
// 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
FAQs
Individual fetch API wrapper for the browser
The npm package http-fetch-json receives a total of 0 weekly downloads. As such, http-fetch-json popularity was classified as not popular.
We found that http-fetch-json demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
At Node Congress, Socket CEO Feross Aboukhadijeh uncovers the darker aspects of open source, where applications that rely heavily on third-party dependencies can be exploited in supply chain attacks.
Research
Security News
The Socket Research team found this npm package includes code for collecting sensitive developer information, including your operating system username, Git username, and Git email.
Security News
OpenJS is warning of social engineering takeovers targeting open source projects after receiving a credible attempt on the foundation.