Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

🐶 A wrapper around Fetch just for JSON (with TypeScript declarations)

License

NotificationsYou must be signed in to change notification settings

center-key/fetch-json

Repository files navigation

logos

A wrapper around Fetch just for JSON

License:MITnpmBuild

Why would you fetch anything but json? ;)

A) Make REST Easy

fetch-json is a lightweight JavaScript library to reduce the boilerplate code needed to makeHTTP calls to JSON endpoints.The minified JS file is under 4 KB.

fetch-json automatically:

  1. Adds the HTTP headerContent-Type: application/json to ensure the correct data type
  2. Runs.json() on the response
  3. Serializes the body payload withJSON.stringify()
  4. Appendsparams to the URL ofGET requests
  5. Setscredentials to'same-origin' (support user sessions in frameworks like Grails, Rails, PHP, Django, Flask, etc.)
  6. Converts the HTTP text response to JSON if it's not already JSON (convenient for handling HTTP errors)
  7. Maps HTTP response headers from aHEAD request into a simple object

fetch-json is ideal for aJAMstack architecture where "dynamicprogramming during the request/response cycle is handled by JavaScript, running entirely on theclient".

B) Setup

1. Web browser

In a web page:

<scriptsrc=fetch-json.min.js></script>

or from thejsdelivr.com CDN:

<scriptsrc=https://cdn.jsdelivr.net/npm/fetch-json@3.3/dist/fetch-json.min.js></script>

2. Node.js server

Install package for node:

$ npm install fetch-json

and then import:

import{fetchJson}from'fetch-json';

Requires minimumnode v18.

If you use GitHub Actions, ensure the version of node is set correclty:

-uses:actions/setup-node@v3with:node-version:18

C) Examples

1. HTTP GET

Fetch the NASA Astronomy Picture of the Day:

// NASA APoDconsturl='https://api.nasa.gov/planetary/apod';constparams={api_key:'DEMO_KEY'};consthandleData=(data)=>console.log('The NASA APoD for today is at:',data.url);fetchJson.get(url,params).then(handleData);

Example output:

> The NASA APoD for today is at:> https://apod.nasa.gov/apod/image/2107/LRVBPIX3M82Crop1024.jpg

2. HTTP POST

Create a resource for the planet Jupiter:

// Create Jupiterconstresource={name:'Jupiter',position:5};consthandleData=(data)=>console.log('New planet:',data);//http response body as an object literalfetchJson.post('https://centerkey.com/rest/',resource).then(handleData).catch(console.error);

For more examples, see the Mocha specification suite:
spec/node.spec.js(Mocha output for eachbuild underRun npm test)

To see a website that incorporatesfetch-json, check out DataDashboard:
data-dashboard.js.org 📊

D) Examples Using async/await

1. HTTP GET

Fetch the NASA Astronomy Picture of the Day:

// NASA APoDconstshow=async()=>{consturl='https://api.nasa.gov/planetary/apod';constparams={api_key:'DEMO_KEY'};constdata=awaitfetchJson.get(url,params);console.log('The NASA APoD for today is at: '+data.url);};show();

2. HTTP POST

Create a resource for the planet Jupiter:

// Create Jupiterconstcreate=async(resource)=>{constdata=awaitfetchJson.post('https://centerkey.com/rest/',resource);console.log('New planet:',data);//http response body as an object literal};create({name:'Jupiter',position:5});

E) Leverages Fetch API

fetch-json calls the nativeFetch API.

For comparison, the POST example in sectionC) Examples to create a planet would bedone calling theFetch APIdirectly with the code:

// Create Jupiter (WITHOUT fetch-json)constresource={name:'Jupiter',position:5};constoptions={method:'POST',headers:{'Content-Type':'application/json','Accept':'application/json',},body:JSON.stringify(resource),};consthandleData=(data)=>console.log(data);//http response body as an object literalfetch('https://centerkey.com/rest/',options).then(response=>response.json()).then(handleData).catch(console.error);

The examplewithfetch-json and the examplewithoutfetch-json each produce the sameoutput.

F) API

1. API — HTTP Request

The format for usingfetch-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);

HEAD (HTTP response headers)

fetchJson.head(url,params,options).then(callback);//headers returned as an object

Notes:

  1. Only theurl parameter is required.  The other parameters are optional.
  2. Theparams object forfetchJson.get() is converted into a query string and appended to theurl.
  3. Theresource object is turned into the body of the HTTP request.
  4. Theoptions parameter is passed through to theFetch API (see theinitdocumentation on MDN).
  5. options is enhanced with a boolean setting forstrictErrors mode (defaultfalse) that throws an error to.catch() whenever the HTTP response status is 400 or higher.

Dynamic HTTP method

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

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

Wheremethod is'GET','POST','PUT','PATCH', or'DELETE', anddata representseitherparams orresource.

2. API — logging

Turn on basic logging to the console with:

fetchJson.enableLogger();

To use a custom logger, pass in a function that accepts 9 parameters to log.

To get an array containing the names of the parameters:

fetchJson.getLogHeaders();// 'Timestamp', 'HTTP', 'Method', 'Domain', 'URL', 'Ok', 'Status', 'Text', 'Type'

The default console output looks like:
2018-09-12T07:20:12.372Z – "request" - "GET" – "api.nasa.gov" – "https://api.nasa.gov/planetary/apod"
2018-09-12T07:20:13.009Z – "response" - "GET" – "api.nasa.gov" – "https://api.nasa.gov/planetary/apod" - true - 200 - "OK" - "application/json"

Turn off logging with:

fetchJson.enableLogger();

G) Response Text and Errors Converted to JSON

The HTTP response body is considered to be JSON if theContent-Type is"application/json" or"text/javascript". If the HTTP response body is not JSON,fetch-json passes backthrough the promise an object with abodyText string field containing response body text.

In addition to thebodyText field, the object will have the fields:ok,status,statusText,contentType, anddata. If an HTML error response is JSON, thedata will contain the parsed JSON.

For example, an HTTP response for an error status of 500 would be converted to an objectsimilar to:

{ok:false,status:500,statusText:'INTERNAL SERVER ERROR',contentType:'text/html; charset=utf-8',bodyText:'<!doctype html><html lang=en><body>Server Error</body></html>',data:null,}

Every response that is not JSON or is an HTTP error will be consistently formatted like the object above. Withfetch-json you know the response will always be passed back to you as a consistent,simple object literal.

H) Base Options

UsefetchJson.setBaseOptions() to configure options to be used on futurefetchJson requests.

The example below sets theAuthorization HTTP header so it is sent on the subsequent GET andDELETE requests:

fetchJson.setBaseOptions({headers:{Authorization:'Basic WE1MIGlzIGhpZGVvdXM='}});fetchJson.get('https://dna-engine.org/api/books/').then(display);//with auth headerfetchJson.delete('https://dna-engine.org/api/books/3/');//with auth header

To have multiple base options available at the same time, use theFetchJson class to instantiatemultiple copies offetchJson:

import{FetchJson}from'fetch-json';constfetchJsonA=newFetchJson({headers:{From:'aaa@example.com'}}).fetchJson;constfetchJsonB=newFetchJson({headers:{From:'bbb@example.com'}}).fetchJson;fetchJsonA.get('https://dna-engine.org/api/books/').then(display);//from aaa@example.comfetchJsonB.delete('https://dna-engine.org/api/books/3/');//from bbb@example.com

I) TypeScript Declarations

See the TypeScript declarations at the top of thefetch-json.ts file.

The declarations provide type information about the API. For example, thefetchJson.post()function returns aPromise for aFetchResponse:

fetchJson.post(url:string,resource?:RequestData,options?:FetchOptions):Promise<FetchResponse>

J) Fetch polyfills

1. Add Fetch to JSDOM

JSDOM does not includefetch, so you need to add a polyfill.

$ npm install --save-dev whatwg-fetch

See usage ofwhatwg-fetch inspec/jsdom.spec.js.

2. Legacy Node.js

Native support forFetch API was introduced innode v18 which became the Active LTS version on 2022-10-25. If you're using an older version ofnode, stick withfetch-json v2.7 and in yourpackage.json file declare a dependency on thenode-fetch polyfill package.

$ npm install node-fetch

K) Build Environment

Check out therunScriptsConfig section inpackage.json for aninteresting approach to organizing build tasks.

CLI Build Tools for package.json

  • 🎋add-dist-headerPrepend a one-line banner comment (with license notice) to distribution files
  • 📄copy-file-utilCopy or rename a file with optional package version number
  • 📂copy-folder-utilRecursively copy files from one folder to another folder
  • 🪺recursive-execRun a command on each file in a folder and its subfolders
  • 🔍replacer-utilFind and replace strings or template outputs in text files
  • 🔢rev-web-assetsRevision web asset filenames with cache busting content hash fingerprints
  • 🚆run-scripts-utilOrganize npm package.json scripts into groups of easy to manage commands
  • 🚦w3c-html-validatorCheck the markup validity of HTML files using the W3C validator


"Stop trying to make fetch happen without#fetchJson!"

Feel free to submit questions at:
github.com/center-key/fetch-json/issues

MIT License


[8]ページ先頭

©2009-2025 Movatter.jp