Security News
Introducing the Socket Python SDK
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
node-fetch
Advanced tools
The node-fetch package is a light-weight module that brings window.fetch to Node.js. It is designed to provide a fetch-first, URL-friendly way to access resources across the network.
Simple GET Request
This code performs a simple GET request to the GitHub API and logs the response data.
const fetch = require('node-fetch');
fetch('https://api.github.com/users/github')
.then(response => response.json())
.then(data => console.log(data));
POST Request with JSON
This code sends a POST request with a JSON body to httpbin.org and logs the response JSON.
const fetch = require('node-fetch');
fetch('https://httpbin.org/post', {
method: 'post',
body: JSON.stringify({foo: 'bar'}),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
Handling Network Errors
This code attempts to fetch a resource from an invalid domain and catches network errors.
const fetch = require('node-fetch');
fetch('https://domain.invalid')
.catch(err => console.error('Network error:', err));
Stream Response
This code fetches an image from GitHub and streams it to a file.
const fetch = require('node-fetch');
const fs = require('fs');
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
Axios is a promise-based HTTP client for the browser and Node.js. It supports interceptors, request/response transformations, and automatic transforms for JSON data. Axios is often considered more feature-rich than node-fetch, with built-in support for interceptors and a wider range of HTTP request methods.
Got is a human-friendly and powerful HTTP request library for Node.js. It provides a simpler and more comprehensive API than node-fetch, with features like retries, pagination, and streams. Got is designed to be a more robust and versatile alternative to node-fetch, with additional convenience methods and options.
Superagent is a small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features. Compared to node-fetch, Superagent offers a more fluent and flexible API, with methods for building queries and handling responses in a more expressive way.
Request is a simplified HTTP request client for Node.js, which has been deprecated. It was known for its simplicity and wide adoption but has been replaced by more modern libraries like node-fetch. Despite its deprecation, it was once a popular alternative with a callback-based API.
A light-weight module that brings window.fetch
to Node.js
Instead of implementing XMLHttpRequest
in Node.js to run browser-specific Fetch polyfill, why not go from native http
to Fetch
API directly? Hence node-fetch
, minimal code for a window.fetch
compatible API on Node.js runtime.
See Matt Andrews' isomorphic-fetch for isomorphic usage (exports node-fetch
for server-side, whatwg-fetch
for client-side).
window.fetch
API.res.text()
and res.json()
) to UTF-8 automatically.window.fetch
offers, feel free to open an issue.npm install node-fetch --save
import fetch from 'node-fetch';
// or
// const fetch = require('node-fetch');
// if you are using your own Promise library, set it through fetch.Promise. Eg.
// import Bluebird from 'bluebird';
// fetch.Promise = Bluebird;
// plain text or html
fetch('https://github.com/')
.then(res => res.text())
.then(body => console.log(body));
// json
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(json => console.log(json));
// catching network error
// 3xx-5xx responses are NOT network errors, and should be handled in then()
// you only need one catch() at the end of your promise chain
fetch('http://domain.invalid/')
.catch(err => console.error(err));
// stream
// the node.js way is to use stream when possible
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => {
const dest = fs.createWriteStream('./octocat.png');
res.body.pipe(dest);
});
// buffer
// if you prefer to cache binary data in full, use buffer()
// note that buffer() is a node-fetch only API
import fileType from 'file-type';
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => res.buffer())
.then(buffer => fileType(buffer))
.then(type => { /* ... */ });
// meta
fetch('https://github.com/')
.then(res => {
console.log(res.ok);
console.log(res.status);
console.log(res.statusText);
console.log(res.headers.raw());
console.log(res.headers.get('content-type'));
});
// post
fetch('http://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json())
.then(json => console.log(json));
// post with stream from file
import { createReadStream } from 'fs';
const stream = createReadStream('input.txt');
fetch('http://httpbin.org/post', { method: 'POST', body: stream })
.then(res => res.json())
.then(json => console.log(json));
// post with JSON
var body = { a: 1 };
fetch('http://httpbin.org/post', {
method: 'POST',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => console.log(json));
// post with form-data (detect multipart)
import FormData from 'form-data';
const form = new FormData();
form.append('a', 1);
fetch('http://httpbin.org/post', { method: 'POST', body: form })
.then(res => res.json())
.then(json => console.log(json));
// post with form-data (custom headers)
// note that getHeaders() is non-standard API
import FormData from 'form-data';
const form = new FormData();
form.append('a', 1);
fetch('http://httpbin.org/post', { method: 'POST', body: form, headers: form.getHeaders() })
.then(res => res.json())
.then(json => console.log(json));
// node 7+ with async function
(async function () {
const res = await fetch('https://api.github.com/users/github');
const json = await res.json();
console.log(json);
})();
See test cases for more examples.
Returns a Promise
Should be an absolute url, eg http://example.com/
Note that only method
, headers
, redirect
and body
are allowed in window.fetch
. Other options are node.js extensions. The default values are shown after each option key.
{
method: 'GET'
, headers: {} // request header. format {a:'1'} or {b:['1','2','3']}
, redirect: 'follow' // set to `manual` to extract redirect headers, `error` to reject redirect
, follow: 20 // maximum redirect count. 0 to not follow redirect
, timeout: 0 // req/res timeout in ms, it resets on redirect. 0 to disable (OS limit applies)
, compress: true // support gzip/deflate content encoding. false to disable
, size: 0 // maximum response body size in bytes. 0 to disable
, body: empty // request body. can be a string, buffer, readable stream
, agent: null // http.Agent instance, allows custom proxy, certificate etc.
}
MIT
Thanks to github/fetch for providing a solid implementation reference.
FAQs
A light-weight module that brings Fetch API to node.js
The npm package node-fetch receives a total of 52,263,124 weekly downloads. As such, node-fetch popularity was classified as popular.
We found that node-fetch demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 5 open source maintainers collaborating on the project.
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.
Security News
The initial version of the Socket Python SDK is now on PyPI, enabling developers to more easily interact with the Socket REST API in Python projects.
Security News
Floating dependency ranges in npm can introduce instability and security risks into your project by allowing unverified or incompatible versions to be installed automatically, leading to unpredictable behavior and potential conflicts.
Security News
A new Rust RFC proposes "Trusted Publishing" for Crates.io, introducing short-lived access tokens via OIDC to improve security and reduce risks associated with long-lived API tokens.