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.
- URL. String (Required)
- 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