Skip to content

Latest commit

 

History

History
83 lines (72 loc) · 2.65 KB

README.md

File metadata and controls

83 lines (72 loc) · 2.65 KB

node-fetch-json

A very thin wrapper around node-fetch just for JSON

License: MIT   npm   Known Vulnerabilities   Build Status

Why would you fetch anything but json? ;)

A) Setup

Install with the command:

$ npm install node-fetch-json --save

Then import with the line:

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

B) Usage

node-fetch-json depends on and calls node-fetch.

1. The low-level way

node-fetch enables you to send and receive JSON at a REST endpoint using:

const fetch = require('node-fetch');
const data = { animal: 'dog', action: 'fetch' };
const options = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        },
    body: JSON.stringify(data)
    };
function handleJson(data) {
    console.log(data.origin, data.json);
    }
fetch('https://httpbin.org/post', options)
    .then(response => response.json())
    .then(handleJson)
    .catch(console.log);

2. A more concise way

With node-fetch-json, the above becomes:

const fetchJson = require('node-fetch-json');
const data = { animal: 'dog', action: 'fetch' };
function handleJson(data) {
    console.log(data.origin, data.json);
    }
fetchJson('https://httpbin.org/post', { method: 'POST', body: data })
    .then(handleJson)
    .catch(console.log);

3. Same result

Both examples produce output that looks like:
203.0.113.254 { action: 'fetch', animal: 'dog' }

C) Details

The node-fetch-json module:

  1. Automatically adds the JSON data type ('application/json') to the HTTP headers.
  2. Automatically serializes the body payload with JSON.stringify().
  3. Automatically runs .json() on the response promise.

The format for using node-fetch-json is:

fetchJson(url[, options])

The url and options parameters are passed through to node-fetch. See the documentation for the node-fetch project.

D) Questions or enhancements

Feel free to submit an issue.


MIT License