Socket
Socket
Sign inDemoInstall

browser-fetch-json

Package Overview
Dependencies
0
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    browser-fetch-json

A thin wrapper around the Fetch API just for JSON in the browser


Version published
Weekly downloads
1
Maintainers
1
Install size
136 kB
Created
Weekly downloads
 

Readme

Source

browser-fetch-json

<img src=https://raw.githubusercontent.com/center-key/browser-fetch-json/master/logos.png align=right width=200 alt=logos>

A thin wrapper around the Fetch API just for JSON in the browser

License: MIT   npm   Known Vulnerabilities   Build Status

Why would you fetch anything but json? ;)

1) Setup

In a web page:

<script src=browser-fetch-json.min.js></script>

From the jsdelivr.com CDN:

<script src=https://cdn.jsdelivr.net/npm/browser-fetch-json@0.1/browser-fetch-json.min.js></script>

Or install as a module:

$ npm install browser-fetch-json

Then import with:

const fetchJson = require('browser-fetch-json');

2) Examples

HTTP GET

Fetch the NASA Astronomy Picture of the Day:

// NASA APOD
const url =    'https://api.nasa.gov/planetary/apod';
const params = { api_key: 'DEMO_KEY' };
function handleData(data) {
   console.log('The NASA APOD for today is at: ' + data.url);
   }
fetchJson.get(url, params).then(handleData);
HTTP POST

Create a resource for the planet Jupiter:

// Create Jupiter
const resource = { name: 'Jupiter', position: 5 };
function handleData(data) {
   console.log(data);  //HTTP response body as an object literal
   }
fetchJson.post('https://httpbin.org/post', resource)
   .then(handleData)
   .catch(console.error);

3) Leverages the Fetch API

browser-fetch-json uses the browser's native Fetch API.

For comparison, the above POST example to create a planet would be done directly using the Fetch API with the code:

// Create Jupiter (with Fetch API instead of browser-fetch-json)
const resource = { name: 'Jupiter', position: 5 };
const options = {
   method: 'POST',
   headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
      },
   body: JSON.stringify(resource)
   };
function handleData(data) {
   console.log(data);  //HTTP response body as an object literal
   }
fetch('https://httpbin.org/post', options)
   .then(response => response.json())
   .then(handleData)
   .catch(console.error);

The examples for browser-fetch-json and the Fetch API each produce the same output.

4) Details

The browser-fetch-json module automatically:

  1. Serializes the body payload with JSON.stringify().
  2. Adds the JSON data type ('application/json') to the HTTP headers.
  3. Builds the URL query string from the params object for GET requests.
  4. Runs .json() on the response from the promise.
  5. Sets credentials to 'same-origin' to support user sessions for frameworks/servers such as Grails, Rails, PHP, Flask, etc.

5) API

The format for using browser-fetch-json is:

GET
fetchJson.get(url, params, options).then(callback);
POST
fetchJson.post(url, resource, options).then(callback);
PUT
fetchJson.put(url, resource, options).then(callback);
PATCH
fetchJson.patch(url, resource, options).then(callback);
DELETE
fetchJson.delete(url, resource, options).then(callback);

Notes:

  1. Only the url parameter is required.  The other parameters are optional.
  2. The params object for fetchJson.get() is converted into a query string and appended to the url.
  3. The resource object is turned into the body of the HTTP request.
  4. The options parameter is passed through to the Fetch API (see the MDN Fetch API documentation for supported init options).
Dynamic HTTP method

If you need to programmatically set the method, use the format:

fetchJson.request(method, url, data, options).then(callback);

Where method is 'GET', 'POST', 'PUT', 'PATCH', or 'DELETE', and data represents either params or resource.

Logging

Enable basic logging to the console with:

fetchJson.enableLogger();

Pass in a function to use a custom logger or pass in false to disable logging.

6) Legacy web browsers

To support really old browsers, include polyfills for Promise and Fetch API:

<script src=https://cdn.jsdelivr.net/npm/promise-polyfill@8.1/dist/polyfill.min.js></script>
<script src=https://cdn.jsdelivr.net/npm/whatwg-fetch@2.0/fetch.min.js></script>

For a node version, see: node-fetch-json

8) Questions or enhancements

Feel free to submit an issue.


MIT License

Keywords

FAQs

Last updated on 30 Aug 2018

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc