Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including fetch-lite with all npm packages installed. Try it out:

var fetchLite = require("fetch-lite")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

fetch-lite v1.1.0

A lightweight module to send HTTP(s) requests from Node.js.

Build Status

fetch-lite

A lightweight module to send HTTP(s) requests from Node.js.

  • Not dependent on any third party modules.
  • Purely based on Node.Js http.request client.
  • Written in less than 30 lines. 😳
  • Implements just the fetch() function and nothing else.
  • Returns Promise (so works with async/await).

Whats missing?

  • File Upload (multipart/form-data)
  • Streaming.

Install

Install using npm.

npm install --save fetch-lite

OR Using yarn.

yarn install --save fetch-lite

Usage

The idea of fetch-lite is to create a minimal version of fetch() API described here. A basic GET request is shown below.

const fetch = require('fetch-lite');

fetch('https://httpbin.org/get')
.then(response => console.log(response))
.catch(err => console.error(err));

Using async/await.

(async () => {
    const response = await fetch('https://httpbin.org/get');
    console.log(response);
})();

Post

Posting a post body.

fetch('http://httpbin.org/post', {
    method: 'POST',
    body: {
        hello: 'world'
    }
})
.then(response => console.log(response))
.catch(err => console.error(err));

Posting a JSON body.

fetch('http://httpbin.org/post', {
    method: 'POST',
    body: {
        hello: 'world'
    },
    headers: {
        'content-type': 'application/json'
    }
})
.then(response => console.log(response))
.catch(err => console.error(err));

Posting a Buffer.

fetch('http://httpbin.org/post', {
    method: 'POST',
    body: Buffer.from("Hello World")
})
.then(response => console.log(response))
.catch(err => console.error(err));

Basic auth

fetch('https://httpbin.org/basic-auth/user/passwd', {
    auth: "user:passwd"
})
.then(response => assertEq(response.status, 200))
.catch(err => breakWithErr(err));

API

The module export one function which accepts only 2 params.

  1. URL. String (Required)
  2. Options. Object. (Optional)
    • method. String. (POST | GET | PUT etc). Default GET.
    • body. String or Object or Buffer.
    • headers. Object.
    • auth. String. Used to set the Basic auth header. Format "username/password".
    • followredirect. Boolean. Default True.

Output Params:

  • headers. Object
  • statusText. String
  • status. Number
  • url. String
  • body. String or Object

Licence

MIT

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free