A light-weight module that brings the Fetch API to Node.js

Overview
Node Fetch

A light-weight module that brings Fetch API to Node.js.

Build status Coverage status Current version Install size Mentioned in Awesome Node.js Discord

Consider supporting us on our Open Collective:

Open Collective

Motivation

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 Jason Miller's isomorphic-unfetch or Leonardo Quixada's cross-fetch for isomorphic usage (exports node-fetch for server-side, whatwg-fetch for client-side).

Features

  • Stay consistent with window.fetch API.
  • Make conscious trade-off when following WHATWG fetch spec and stream spec implementation details, document known differences.
  • Use native promise and async functions.
  • Use native Node streams for body, on both request and response.
  • Decode content encoding (gzip/deflate/brotli) properly, and convert string output (such as res.text() and res.json()) to UTF-8 automatically.
  • Useful extensions such as redirect limit, response size limit, explicit errors for troubleshooting.

Difference from client-side fetch

  • See known differences:
  • If you happen to use a missing feature that window.fetch offers, feel free to open an issue.
  • Pull requests are welcomed too!

Installation

Current stable release (3.x)

npm install node-fetch

Loading and configuring the module

// CommonJS
const fetch = require('node-fetch');

// ES Module
import fetch from 'node-fetch';

If you want to patch the global object in node:

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

if (!globalThis.fetch) {
	globalThis.fetch = fetch;
}

For versions of Node earlier than 12, use this globalThis polyfill.

Upgrading

Using an old version of node-fetch? Check out the following files:

Common Usage

NOTE: The documentation below is up-to-date with 3.x releases, if you are using an older version, please check how to upgrade.

Plain text or HTML

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

const response = await fetch('https://github.com/');
const body = await response.text();

console.log(body);

JSON

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

const response = await fetch('https://api.github.com/users/github');
const data = await response.json();

console.log(data);

Simple Post

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

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'});
const data = await response.json();

console.log(data);

Post with JSON

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

const body = {a: 1};

const response = await fetch('https://httpbin.org/post', {
	method: 'post',
	body: JSON.stringify(body),
	headers: {'Content-Type': 'application/json'}
});
const data = await response.json();

console.log(data);

Post with form parameters

URLSearchParams is available on the global object in Node.js as of v10.0.0. See official documentation for more usage methods.

NOTE: The Content-Type header is only set automatically to x-www-form-urlencoded when an instance of URLSearchParams is given as such:

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

const params = new URLSearchParams();
params.append('a', 1);

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: params});
const data = await response.json();

console.log(data);

Handling exceptions

NOTE: 3xx-5xx responses are NOT exceptions, and should be handled in then(), see the next section.

Wrapping the fetch function into a try/catch block will catch all exceptions, such as errors originating from node core libraries, like network errors, and operational errors which are instances of FetchError. See the error handling document for more details.

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

try {
	await fetch('https://domain.invalid/');
} catch (error) {
	console.log(error);
}

Handling client and server errors

It is common to create a helper function to check that the response contains no client (4xx) or server (5xx) error responses:

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

class HTTPResponseError extends Error {
	constructor(response, ...args) {
		this.response = response;
		super(`HTTP Error Response: ${response.status} ${response.statusText}`, ...args);
	}
}

const checkStatus = response => {
	if (response.ok) {
		// response.status >= 200 && response.status < 300
		return response;
	} else {
		throw new HTTPResponseError(response);
	}
}

const response = await fetch('https://httpbin.org/status/400');

try {
	checkStatus(response);
} catch (error) {
	console.error(error);

	const errorBody = await error.response.text();
	console.error(`Error body: ${errorBody}`);
}

Handling cookies

Cookies are not stored by default. However, cookies can be extracted and passed by manipulating request and response headers. See Extract Set-Cookie Header for details.

Advanced Usage

Streams

The "Node.js way" is to use streams when possible. You can pipe res.body to another stream. This example uses stream.pipeline to attach stream error handlers and wait for the download to complete.

const {createWriteStream} = require('fs');
const {pipeline} = require('stream');
const {promisify} = require('util');
const fetch = require('node-fetch');

const streamPipeline = promisify(pipeline);

const response = await fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png');

if (!response.ok) throw new Error(`unexpected response ${response.statusText}`);

await streamPipeline(response.body, createWriteStream('./octocat.png'));

In Node.js 14 you can also use async iterators to read body; however, be careful to catch errors -- the longer a response runs, the more likely it is to encounter an error.

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

const response = await fetch('https://httpbin.org/stream/3');

try {
	for await (const chunk of response.body) {
		console.dir(JSON.parse(chunk.toString()));
	}
} catch (err) {
	console.error(err.stack);
}

In Node.js 12 you can also use async iterators to read body; however, async iterators with streams did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors directly from the stream and wait on it response to fully close.

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

const read = async body => {
	let error;
	body.on('error', err => {
		error = err;
	});

	for await (const chunk of body) {
		console.dir(JSON.parse(chunk.toString()));
	}

	return new Promise((resolve, reject) => {
		body.on('close', () => {
			error ? reject(error) : resolve();
		});
	});
};

try {
	const response = await fetch('https://httpbin.org/stream/3');
	await read(response.body);
} catch (err) {
	console.error(err.stack);
}

Buffer

If you prefer to cache binary data in full, use buffer(). (NOTE: buffer() is a node-fetch only API)

const fetch = require('node-fetch');
const fileType = require('file-type');

const response = await fetch('https://octodex.github.com/images/Fintechtocat.png');
const buffer = await response.buffer();
const type = await fileType.fromBuffer(buffer)

console.log(type);

Accessing Headers and other Meta data

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

const response = await fetch('https://github.com/');

console.log(response.ok);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers.raw());
console.log(response.headers.get('content-type'));

Extract Set-Cookie Header

Unlike browsers, you can access raw Set-Cookie headers manually using Headers.raw(). This is a node-fetch only API.

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

const response = await fetch('https://example.com');

// Returns an array of values, instead of a string of comma-separated values
console.log(response.headers.raw()['set-cookie']);

Post data using a file stream

const {createReadStream} = require('fs');
const fetch = require('node-fetch');

const stream = createReadStream('input.txt');

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: stream});
const data = await response.json();

console.log(data)

Post with form-data (detect multipart)

const fetch = require('node-fetch');
const FormData = require('form-data');

const form = new FormData();
form.append('a', 1);

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});
const data = await response.json();

console.log(data)

// OR, using custom headers
// NOTE: getHeaders() is non-standard API

const options = {
	method: 'POST',
	body: form,
	headers: form.getHeaders()
};

const response = await fetch('https://httpbin.org/post', options);
const data = await response.json();

console.log(data)

node-fetch also supports spec-compliant FormData implementations such as form-data and formdata-node:

const fetch = require('node-fetch');
const FormData = require('formdata-node');

const form = new FormData();
form.set('greeting', 'Hello, world!');

const response = await fetch('https://httpbin.org/post', {method: 'POST', body: form});
const data = await response.json();

console.log(data);

Request cancellation with AbortSignal

You may cancel requests with AbortController. A suggested implementation is abort-controller.

An example of timing out a request after 150ms could be achieved as the following:

const fetch = require('node-fetch');
const AbortController = require('abort-controller');

const controller = new AbortController();
const timeout = setTimeout(() => {
	controller.abort();
}, 150);

try {
	const response = await fetch('https://example.com', {signal: controller.signal});
	const data = await response.json();
} catch (error) {
	if (error instanceof fetch.AbortError) {
		console.log('request was aborted');
	}
} finally {
	clearTimeout(timeout);
}

See test cases for more examples.

API

fetch(url[, options])

  • url A string representing the URL for fetching
  • options Options for the HTTP(S) request
  • Returns: Promise<Response>

Perform an HTTP(S) fetch.

url should be an absolute url, such as https://example.com/. A path-relative URL (/file/under/root) or protocol-relative URL (//can-be-http-or-https.com/) will result in a rejected Promise.

Options

The default values are shown after each option key.

{
	// These properties are part of the Fetch Standard
	method: 'GET',
	headers: {},            // Request headers. format is the identical to that accepted by the Headers constructor (see below)
	body: null,             // Request body. can be null, a string, a Buffer, a Blob, or a Node.js Readable stream
	redirect: 'follow',     // Set to `manual` to extract redirect headers, `error` to reject redirect
	signal: null,           // Pass an instance of AbortSignal to optionally abort requests

	// The following properties are node-fetch extensions
	follow: 20,             // maximum redirect count. 0 to not follow redirect
	compress: true,         // support gzip/deflate content encoding. false to disable
	size: 0,                // maximum response body size in bytes. 0 to disable
	agent: null,            // http(s).Agent instance or function that returns an instance (see below)
	highWaterMark: 16384,   // the maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource.
	insecureHTTPParser: false	// Use an insecure HTTP parser that accepts invalid HTTP headers when `true`.
}

Default Headers

If no values are set, the following request headers will be sent automatically:

Header Value
Accept-Encoding gzip,deflate,br (when options.compress === true)
Accept */*
Connection close (when no options.agent is present)
Content-Length (automatically calculated, if possible)
Transfer-Encoding chunked (when req.body is a stream)
User-Agent node-fetch

Note: when body is a Stream, Content-Length is not set automatically.

Custom Agent

The agent option allows you to specify networking related options which are out of the scope of Fetch, including and not limited to the following:

  • Support self-signed certificate
  • Use only IPv4 or IPv6
  • Custom DNS Lookup

See http.Agent for more information.

In addition, the agent option accepts a function that returns http(s).Agent instance given current URL, this is useful during a redirection chain across HTTP and HTTPS protocol.

const http = require('http');
const https = require('https');

const httpAgent = new http.Agent({
	keepAlive: true
});
const httpsAgent = new https.Agent({
	keepAlive: true
});

const options = {
	agent: function(_parsedURL) {
		if (_parsedURL.protocol == 'http:') {
			return httpAgent;
		} else {
			return httpsAgent;
		}
	}
};

Custom highWaterMark

Stream on Node.js have a smaller internal buffer size (16kB, aka highWaterMark) from client-side browsers (>1MB, not consistent across browsers). Because of that, when you are writing an isomorphic app and using res.clone(), it will hang with large response in Node.

The recommended way to fix this problem is to resolve cloned response in parallel:

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

const response = await fetch('https://example.com');
const r1 = await response.clone();

const results = await Promise.all([response.json(), r1.text()]);

console.log(results[0]);
console.log(results[1]);

If for some reason you don't like the solution above, since 3.x you are able to modify the highWaterMark option:

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

const response = await fetch('https://example.com', {
	// About 1MB
	highWaterMark: 1024 * 1024
});

const result = await res.clone().buffer();
console.dir(result);

Insecure HTTP Parser

Passed through to the insecureHTTPParser option on http(s).request. See http.request for more information.

Class: Request

An HTTP(S) request containing information about URL, method, headers, and the body. This class implements the Body interface.

Due to the nature of Node.js, the following properties are not implemented at this moment:

  • type
  • destination
  • referrer
  • referrerPolicy
  • mode
  • credentials
  • cache
  • integrity
  • keepalive

The following node-fetch extension properties are provided:

  • follow
  • compress
  • counter
  • agent
  • highWaterMark

See options for exact meaning of these extensions.

new Request(input[, options])

(spec-compliant)

  • input A string representing a URL, or another Request (which will be cloned)
  • options [Options][#fetch-options] for the HTTP(S) request

Constructs a new Request object. The constructor is identical to that in the browser.

In most cases, directly fetch(url, options) is simpler than creating a Request object.

Class: Response

An HTTP(S) response. This class implements the Body interface.

The following properties are not implemented in node-fetch at this moment:

  • Response.error()
  • Response.redirect()
  • type
  • trailer

new Response([body[, options]])

(spec-compliant)

Constructs a new Response object. The constructor is identical to that in the browser.

Because Node.js does not implement service workers (for which this class was designed), one rarely has to construct a Response directly.

response.ok

(spec-compliant)

Convenience property representing if the request ended normally. Will evaluate to true if the response status was greater than or equal to 200 but smaller than 300.

response.redirected

(spec-compliant)

Convenience property representing if the request has been redirected at least once. Will evaluate to true if the internal redirect counter is greater than 0.

Class: Headers

This class allows manipulating and iterating over a set of HTTP headers. All methods specified in the Fetch Standard are implemented.

new Headers([init])

(spec-compliant)

  • init Optional argument to pre-fill the Headers object

Construct a new Headers object. init can be either null, a Headers object, an key-value map object or any iterable object.

// Example adapted from https://fetch.spec.whatwg.org/#example-headers-class
const {Headers} = require('node-fetch');

const meta = {
	'Content-Type': 'text/xml',
	'Breaking-Bad': '<3'
};
const headers = new Headers(meta);

// The above is equivalent to
const meta = [['Content-Type', 'text/xml'], ['Breaking-Bad', '<3']];
const headers = new Headers(meta);

// You can in fact use any iterable objects, like a Map or even another Headers
const meta = new Map();
meta.set('Content-Type', 'text/xml');
meta.set('Breaking-Bad', '<3');
const headers = new Headers(meta);
const copyOfHeaders = new Headers(headers);

Interface: Body

Body is an abstract interface with methods that are applicable to both Request and Response classes.

The following methods are not yet implemented in node-fetch at this moment:

  • formData()

body.body

(deviation from spec)

Data are encapsulated in the Body object. Note that while the Fetch Standard requires the property to always be a WHATWG ReadableStream, in node-fetch it is a Node.js Readable stream.

body.bodyUsed

(spec-compliant)

  • Boolean

A boolean property for if this body has been consumed. Per the specs, a consumed body cannot be used again.

body.arrayBuffer()

body.blob()

body.json()

body.text()

(spec-compliant)

  • Returns: Promise

Consume the body and return a promise that will resolve to one of these formats.

body.buffer()

(node-fetch extension)

  • Returns: Promise

Consume the body and return a promise that will resolve to a Buffer.

Class: FetchError

(node-fetch extension)

An operational error in the fetching process. See ERROR-HANDLING.md for more info.

Class: AbortError

(node-fetch extension)

An Error thrown when the request is aborted in response to an AbortSignal's abort event. It has a name property of AbortError. See ERROR-HANDLING.MD for more info.

TypeScript

Since 3.x types are bundled with node-fetch, so you don't need to install any additional packages.

For older versions please use the type definitions from DefinitelyTyped:

npm install --save-dev @types/node-fetch

Acknowledgement

Thanks to github/fetch for providing a solid implementation reference.

Team

David Frank Jimmy Wärting Antoni Kepinski Richie Bendall Gregor Martynus
David Frank Jimmy Wärting Antoni Kepinski Richie Bendall Gregor Martynus
Former

License

MIT

Comments
  • v3 Roadmap

    v3 Roadmap

    Note: v3 beta is now available on npm under the next tag


    v3 Roadmap

    General stuff

    • [x] BREAKING: Drop support for Node.js 4 and Node.js 6 (#489, #624)
    • [x] Update devDependencies (related to #489)
    • [x] When users clone(), automatically create streams with custom highWaterMark (#386, PR open: #671)
    • [x] Bundle TypeScript types (Support for TypeScript without need of installing @types/node-fetch package) (#669)
    • [x] Replace Rollup with Microbundle (#643)
    • [x] Introduce linting to the project (#303)
    • [x] Simplify Travis CI build matrix (related to #431) - Dropping support for Node.js 4 & 6 will help
    • [x] Response.statusText should not default (#578)
    • [x] Use w3c defined message for AbortError (#657)
    • [x] URL is not encoded as UTF-8 (#245)
    • Deprecate timeout in favor of AbortController (#523)
    • [x] Data URI support (#659)
    • [x] Drop the optional dependency on encoding and move charset detection into a separate package. (In progress: Richienb/fetch-charset-detection (PR Open: #694))
    • [x] Drop existing blob implementation code and use fetch-blob as dependency instead (https://github.com/bitinn/node-fetch/issues/668#issuecomment-529175627)
    • [x] Fix stream piping (#309, PR open: #670)
    • [x] Fix stream resolving (#642, #665)
    • [x] Do not use constructor.name to check object (#667, PR open: #673)
    • [x] Properly forward request errors while piping response stream
    • [x] Convert Content-Encoding to lowercase (#661, PR open: #672)
    • [x] More tests for data URI (https://github.com/bitinn/node-fetch/issues/668#issuecomment-529175096)
    • [ ] Drop credentials before redirection (#274)
    • [x] Modernise the code behind FetchError and AbortError (https://github.com/bitinn/node-fetch/issues/668#issuecomment-530845161)
    • [x] Propagate size and timeout to cloned response (#664)
    • [x] Replace the calls to url.parse and url.resolve with calls to new URL to use the new UTF-8 awareness and remove the utf8 package.
      • [x] url.parse (https://github.com/node-fetch/node-fetch/pull/701)
      • [x] url.resolve (https://github.com/bitinn/node-fetch/commit/e3cd4d22c3f1871fb41b17035ac83b47ad57fdf6)
    • [ ] Document types of fetch errors more thoroughly (#549)
    • [ ] Should update host if there's a redirection (#570, PR Open: #596)
    • [x] High priority doesn't correctly handle multiple content-type values (#783)

    Additional:

    • [ ] HTTP/2 support (#342, PR open: #796)
    • [ ] Plugin/middleware system (https://github.com/bitinn/node-fetch/issues/668#issuecomment-533544800, PR open: #677)
    • ~~WebStream API support (#387)~~ - needs more discussion and standard.
    • ~~Support trailers (#330)~~ - trailer support has been removed (whatwg/fetch#772).
    • ~~Caching (#68)~~ - would likely require opinionated implementation.
    • ~~Cookies (#94)~~ - would likely require opinionated implementation.

    Other


    cc @bitinn @jimmywarting @TimothyGu @jkantr @gr2m @Richienb

    help wanted meta 
    opened by xxczaki 215
  • chore(cjs/esm): Bundle module and use package exports

    chore(cjs/esm): Bundle module and use package exports

    THIS IS A PROPOSAL

    As explained in #1226, the fact that node-fetch v3.0.0-beta.10 is now pure ESM cause multiple problems with existing codebases.

    In JavaScript codebases, we need to use the async import() which can create a lot of changes. In TypeScript codebases (with cjs module mode), it is impossible to use node-fetch anymore.

    I think that ESM is the future but it is not as stable as we think and it is not ready to be used everywhere. The best way to ensure that all existing codebases can migrate to v3 is to provide both cjs and esm versions of this module.

    For this, I introduced esbuild which can transpile ESM to CJS and also can bundle the package.

    You can say: "node does not need packages to be bundled", which is true. However, bundling is a good practice to reduce the module loading time, disk operations, memory footprint, etc. It can also be used to bundle internal dependencies and so reduce the npm dependency tree (reduce install time, disk operations, memory footprint, npm hell, etc.).

    What is the purpose of this pull request?

    • [ ] Documentation update
    • [X] Bug fix
    • [ ] New feature
    • [X] Other, please explain:
      • allow both esm and cjs exports
      • reduce module loading time
      • reduce disk operations
      • reduce module memory footprint

    What changes did you make? (provide an overview)

    • use esbuild to bundle module in esm and cjs format
    • bundle dependencies to reduce module size
    • use package exports to automatically select the appropriate version
    • add build step to prepublishOnly
    • add build step to ci

    Which issue (if any) does this pull request address?

    #1226 #1217

    Is there anything you'd like reviewers to know?

    In this implementation, I bundle both data-uri-to-buffer and fetch-blob into the final result allowing us to be dependency free.

    I think data-uri-to-buffer is safe to bundle because it's an internal dependency. However, I think fetch-blob should not be bundled because it could be used by the consumer.

    What do you think?

    Note 1: If we do not want to bundle fetch-blob, we have to provide a CJS export for it. Note 2: If we do not bundle fetch-blob, the install size will be very large as mentioned by @akaupi in #1217. Maybe we could make fetch-blob dependency free by using esbuild to bundle web-streams-polyfill .

    opened by SomaticIT 45
  • Cannot find module 'node:http` on AWS Lambda v14

    Cannot find module 'node:http` on AWS Lambda v14

    Upgrade from version 3.0 to 3.1 produces a Runtime.ImportModuleError: Error: Cannot find module 'node:http on AWS Lambda runtime.

    Screenshots

    Screenshot 2021-11-09 at 07 32 57

    Your Environment

    | software | version | ---------------- | ------- | node-fetch |3.1 | node |14

    Additional context

    Looks like node: prefix for imports added as part of https://github.com/node-fetch/node-fetch/pull/1346 causes this issue. I am happy to submit MR with a revert of this one, but I need to understand the reason why this prefix has been added here on the first place. Can you suport me on this one please @dnalborczyk ?

    bug 
    opened by pawelgrzybek 34
  • feat: Implement form-data encoding

    feat: Implement form-data encoding

    This pull request brings support of the spec-compliant FormData in request body. As an example I'm using formdata-node package (for tests and docs).

    Notes on the PR:

    • Differences between form-data and formdata-node: https://github.com/octet-stream/form-data/issues/1
    • Content-Length is not supported for formdata-node because the package only have asynchronous method for that: FormData#getComputedLength()
    • formdata-node requires at least Node 8, but tests seem to work on Node 6 as well. I think, the PR might be delivered in 3.x if you'll drop older Node versions
    • Readable.from is used for data consumption, so the minimal Node.js version is raised to 10.17 (from 10.16)
    enhancement 
    opened by octet-stream 32
  • The future of node-fetch

    The future of node-fetch

    (Sometimes you gotta write a clickbait issue to get people's attention.)

    The current status of node-fetch is fine:

    • I believe 95% of the Fetch API use cases are covered either by us or other implementations.
    • node-fetch is lean enough (150KB, zero dependency), people can write their own wrapper or even fork our code to fit their own purpose.
    • Fetch API is now quite stable so we are not dealing with many breaking changes.
    • In short, if you are on 1.x or 2.x releases, and it works for you, great, no need to worry.

    The future status of node-fetch could be better:

    • It doesn't have an active maintainer, (contributors) all have their own lives.
    • There are certainly things we would like to work on to make node-fetch easier to use. (see open PRs).

    What to do?

    • We need an active maintainer: someone need to own this package's npm publishing right, and have free time and proper motivation to maintain node-fetch changelog and releases.
    • We need a small team that help on non-trivial things: like making a PR spec compliant, which again require free time and proper motivation.

    If you are such a candidate, or better yet, can negotiate with your employer to be payed to maintain node-fetch, let us know in the comments.

    meta 
    opened by bitinn 28
  • refactor: Replace `url.parse` with `new URL()`

    refactor: Replace `url.parse` with `new URL()`

    I think this is the last thing we need to do in order to release the 3.x alpha release.

    Replacing the url.parse API here doesn't break our tests: https://github.com/bitinn/node-fetch/blob/3b452b8e1f280142d78d5a33abf945d77c25ea59/src/request.js#L51

    However, trying to use the new WHATWG API here: https://github.com/bitinn/node-fetch/blob/3b452b8e1f280142d78d5a33abf945d77c25ea59/src/request.js#L54

    throws some errors:

    > [email protected] test /home/akepinski/dev/node-fetch
    > cross-env BABEL_ENV=test mocha --require @babel/register --throw-deprecation test/test.js
    
    
    
      node-fetch
        ✓ should return a promise
        1) should return a promise
    (node:11807) UnhandledPromiseRejectionWarning: FetchError: request to http://localhost:30001/hello failed, reason: connect ECONNREFUSED 127.0.0.1:80
        at ClientRequest.<anonymous> (/home/akepinski/dev/node-fetch/src/index.js:113:11)
        at ClientRequest.emit (events.js:210:5)
        at Socket.socketErrorListener (_http_client.js:406:9)
        at Socket.emit (events.js:210:5)
        at emitErrorNT (internal/streams/destroy.js:92:8)
        at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
        at processTicksAndRejections (internal/process/task_queues.js:80:21)
    (node:11807) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    
    
      1 passing (35ms)
      1 failing
    
      1) node-fetch
           should return a promise:
         Uncaught DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
          at emitDeprecationWarning (internal/process/promises.js:153:11)
          at processPromiseRejections (internal/process/promises.js:205:13)
          at processTicksAndRejections (internal/process/task_queues.js:94:32)
    
    
    
    npm ERR! Test failed.  See above for more details.
    

    Trying to use the new API here also breaks our tests, but with more precise errors:

    175 passing (2s)
      29 failing
    
      1) node-fetch
           should follow redirect code 301:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      2) node-fetch
           should follow redirect code 302:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      3) node-fetch
           should follow redirect code 303:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      4) node-fetch
           should follow redirect code 307:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      5) node-fetch
           should follow redirect code 308:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      6) node-fetch
           should follow redirect chain:
         FetchError: request to http://localhost:30001/redirect/301 failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      7) node-fetch
           should follow POST request redirect code 301 with GET:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      8) node-fetch
           should follow PATCH request redirect code 301 with PATCH:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      9) node-fetch
           should follow POST request redirect code 302 with GET:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      10) node-fetch
           should follow PATCH request redirect code 302 with PATCH:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      11) node-fetch
           should follow redirect code 303 with GET:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      12) node-fetch
           should follow PATCH request redirect code 307 with PATCH:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      13) node-fetch
           should obey maximum redirect, reject case:
    
          AssertionError: expected { type: 'system',
      name: 'FetchError',
      errno: 'ECONNREFUSED',
      code: 'ECONNREFUSED',
      erroredSysCall: [Error: connect ECONNREFUSED 127.0.0.1:80] } to have property 'type' of 'max-redirect', but got 'system'
          + expected - actual
    
          -system
          +max-redirect
          
          at /home/akepinski/dev/node-fetch/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22
          at processTicksAndRejections (internal/process/task_queues.js:93:5)
    
      14) node-fetch
           should obey redirect chain, resolve case:
         FetchError: request to http://localhost:30001/redirect/301 failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      15) node-fetch
           should follow redirect code 301 and keep existing headers:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      16) node-fetch
           should set redirected property on response when redirect:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      17) node-fetch
           should allow custom timeout on redirected requests:
    
          AssertionError: expected { type: 'system',
      name: 'FetchError',
      errno: 'ECONNREFUSED',
      code: 'ECONNREFUSED',
      erroredSysCall: [Error: connect ECONNREFUSED 127.0.0.1:80] } to have property 'type' of 'request-timeout', but got 'system'
          + expected - actual
    
          -system
          +request-timeout
          
          at /home/akepinski/dev/node-fetch/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22
          at processTicksAndRejections (internal/process/task_queues.js:93:5)
    
      18) node-fetch
           should allow redirects to be aborted:
    
          AssertionError: expected { type: 'system',
      name: 'FetchError',
      errno: 'ECONNREFUSED',
      code: 'ECONNREFUSED',
      erroredSysCall: [Error: connect ECONNREFUSED 127.0.0.1:80] } to have property 'name' of 'AbortError', but got 'FetchError'
          + expected - actual
    
          -FetchError
          +AbortError
          
          at /home/akepinski/dev/node-fetch/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22
          at processTicksAndRejections (internal/process/task_queues.js:93:5)
    
      19) node-fetch
           should allow redirected response body to be aborted:
    
          AssertionError: expected { type: 'system',
      name: 'FetchError',
      errno: 'ECONNREFUSED',
      code: 'ECONNREFUSED',
      erroredSysCall: [Error: connect ECONNREFUSED 127.0.0.1:80] } to have property 'name' of 'AbortError', but got 'FetchError'
          + expected - actual
    
          -FetchError
          +AbortError
          
          at /home/akepinski/dev/node-fetch/node_modules/chai-as-promised/lib/chai-as-promised.js:302:22
          at processTicksAndRejections (internal/process/task_queues.js:93:5)
    
      20) node-fetch
           should remove internal AbortSignal event listener after request and response complete without aborting:
         AssertionError: expected promise to be fulfilled but it was rejected with 'FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80'
      
    
      21) node-fetch
           should support fetch with Request instance:
         FetchError: request to http://localhost:30001/hello failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      22) node-fetch
           should support fetch with Node.js URL object:
         FetchError: request to http://localhost:30001/hello failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      23) node-fetch
           should support fetch with WHATWG URL object:
         FetchError: request to http://localhost:30001/hello failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      24) node-fetch
           should support overwrite Request instance:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      25) node-fetch
           supports supplying a lookup function to the agent:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      26) node-fetch
           supports supplying a famliy option to the agent:
         FetchError: request to http://localhost:30001/inspect failed, reason: connect ECONNREFUSED 127.0.0.1:80
          at ClientRequest.<anonymous> (src/index.js:113:11)
          at Socket.socketErrorListener (_http_client.js:406:9)
          at emitErrorNT (internal/streams/destroy.js:92:8)
          at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
          at processTicksAndRejections (internal/process/task_queues.js:80:21)
    
      27) Request
           should override signal on derived Request instances:
         TypeError [ERR_INVALID_URL]: Invalid URL: test
          at onParseError (internal/url.js:243:9)
          at new URL (internal/url.js:319:5)
          at new Request (src/request.js:59:16)
          at Context.<anonymous> (test/test.js:2617:26)
          at processImmediate (internal/timers.js:439:21)
    
      28) Request
           should allow removing signal on derived Request instances:
         TypeError [ERR_INVALID_URL]: Invalid URL: test
          at onParseError (internal/url.js:243:9)
          at new URL (internal/url.js:319:5)
          at new Request (src/request.js:59:16)
          at Context.<anonymous> (test/test.js:2629:26)
          at processImmediate (internal/timers.js:439:21)
    
      29) external encoding
           data uri
             should accept data uri of plain text:
    
          AssertionError: expected '' to equal 'Hello World!'
          + expected - actual
    
          +Hello World!
          
          at equal (test/test.js:2835:44)
    
    
    
    npm ERR! Test failed.  See above for more details.
    
    help wanted 
    opened by xxczaki 27
  • MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

    MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

    Hi there,

    I think there is a regression in version 3.0.

    When I'm using Custom Agent (https) with keepAlive: true option and then just make a bunch of requests. Pretty soon such warnings show up:

    (node:24083) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 data listeners added to [TLSSocket]. Use emitter.setMaxListeners() to increase limit at _addListener (node:events:469:17) at TLSSocket.addListener (node:events:491:10) at TLSSocket.Readable.on (node:internal/streams/readable:876:35) at ClientRequest. (.../node_modules/node-fetch/src/index.js:316:10) at ClientRequest.emit (node:events:394:28) at tickOnSocket (node:_http_client:755:7) at onSocketNT (node:_http_client:815:5) at processTicksAndRejections (node:internal/process/task_queues:84:21)

    The same thing with http, just listeners added not to TLSSocket but to just Socket.

    Reproduction

    Here is a really simple example.

    import https from 'node:https'
    import fetch from 'node-fetch'
    
    const agent = new https.Agent({ keepAlive: true })
    
    async function start () {
      for (let i = 1; i < 1000; i++) {
        await fetch('https://example.com', { agent })
      }
    }
    
    process.on('warning', e => console.warn(e.stack))
    
    start().catch(e => console.error(e))
    

    Steps to reproduce the behavior:

    1. Run this code with node-fetch@3 installed and you will start getting warnings.
    2. Install node-fetch@2 as a dependency, run the same code, and boom, no warnings.

    Expected behavior

    Version 2.6.2 does not produce any warning on the same code. Version 3.0.0 produces warnings.

    Your Environment

    I have been running this on node.js 14 (LTS) and 16 (latest) with the same results.

    | software | version | ---------------- | ------- | node-fetch | 3.0.0 | node | v14.17.6 & v16.9.1 | npm | 6.14.15 & 7.21.1 | Operating System | MacOS 11.5.2 (20G95) & Docker with alpine linux

    bug Hacktoberfest released 
    opened by tamtamchik 25
  • 2.0 stable

    2.0 stable

    @timothygu can we establish a roadmap for that, I see 2.0 alpha marked as main release again, are we going to release stable soon? are there ways to check adoption or do we have people actively testing alpha?

    help wanted meta 
    opened by bitinn 25
  • tasks for considering (2.0 release)

    tasks for considering (2.0 release)

    just collecting some common complain about 1.x release

    • [x] provide some guideline on how to handle rejected promise (failed fetch), this can be caused by many reasons: url, headers.location, network timeout, request config etc; currently the only way to distinguish them is to check error message.
    • [x] provide some alternatives to extract redirect headers, it's not possible with current fetch spec, only the final url will be expose to user when following redirects.
    • [ ] some way for cookies to persist when you do a POST request that redirects (which should be followed by a GET request, often with cookie as credential). Though if we implement extraction for redirect headers we can make this possible (keep the cookie headers for your next GET request).
    • [x] expose Request/Headers/Response interfaces, we don't currently have a Request interface due to the fact that no one are using them.
    • [x] normalize Headers .set and .append to prevent non-string input, it's recommended to already cast your input to String type first.
    • [x] Headers/Response interface should support ES6 features, such as keys() and entries()
    help wanted 
    opened by bitinn 24
  • Implement CODEOWNERS

    Implement CODEOWNERS

    https://github.blog/2017-07-06-introducing-code-owners/

    We have made great strides in Node-Fetch these few months but I feel that things have been moving very fast in this repo even with having every PR reviewed by 3 people before merging.

    So I am introducing CODEOWNERS.

    So basically, we have a set of people that have to approve for Code Changes. Others can also approve like the maintainers, but i suggest we have 2 - 3 people approve the code. As for the 2 -3 people, I think it should be those in the @node-fetch/core for Code Changes.

    For other PR's that don't have code change, we can have both @node-fetch/core and @node-fetch/reviewers take a look at it.

    You might be thinking about why this might be needed.

    In the past week, we merged 27 PR's

    Take a look in the spike of code deletions and additions

    We had two releases and one was a fix.

    So, we definitely need to slow things down ( mainly merging ) and take a look at reviewing code. Reviewing code is as important as writing it.

    image

    image

    image

    If we come to the conclusion of implementing this feature, I can get started on working on a PR.

    help wanted meta 
    opened by NotMoni 23
  • Switch to GitHub Org Sponsor?

    Switch to GitHub Org Sponsor?

    I haven't looked into it, but seems like it would have much better integration than Open Collective.

    We could offer issue-based sponsor if it's a thing, otherwise just getting some small monthly or quarterly contribution would be fine too :)

    question 
    opened by bitinn 23
  • Create-React-App testing fails with ReferenceError: Buffer is not defined

    Create-React-App testing fails with ReferenceError: Buffer is not defined

    Reproduction

    Steps to reproduce the behavior:

    1. Click on the run test icon on WebStorm IDE to run the following test:
      describe("App", () => {
          it("render", () => {
              render(App);
          });
      });
      

    Expected behavior

    Run test successfully.

    Screenshots

    image

    Your Environment

    Node packages and versions:

    ├── @comunica/[email protected]
    ├── @inrupt/[email protected]
    ├── @inrupt/[email protected]
    ├── @inrupt/[email protected]
    ├── @react-three/[email protected]
    ├── @react-three/[email protected]
    ├── @testing-library/[email protected]
    ├── @testing-library/[email protected]
    ├── @testing-library/[email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    ├── [email protected]
    └── [email protected]
    

    | software | version | ---------------- | ------- | node | v19.1.0 | npm | 8.19.3 | Operating System | MacOS Ventura 13.0.1 | Chip | Mac M1 Pro

    Additional context

    • I created my app using create-react-app
    • This is the only test I have, and it's failing
    bug 
    opened by danielbakas 2
  • Provide a single param to request (issue #1620)

    Provide a single param to request (issue #1620)

    Purpose

    Provide a single argument to http request function.

    Changes

    Put all information in option object and do not provide url separately

    Additional information


    • fix #1620
    opened by guillaume-fr 0
  • chore(deps-dev): bump mocha from 9.2.2 to 10.2.0

    chore(deps-dev): bump mocha from 9.2.2 to 10.2.0

    Bumps mocha from 9.2.2 to 10.2.0.

    Release notes

    Sourced from mocha's releases.

    v10.2.0

    10.2.0 / 2022-12-11

    :tada: Enhancements

    • #4945: API: add possibility to decorate ESM name before import (@​j0tunn)

    :bug: Fixes

    :book: Documentation

    v10.1.0

    10.1.0 / 2022-10-16

    :tada: Enhancements

    :nut_and_bolt: Other

    v10.0.0

    10.0.0 / 2022-05-01

    :boom: Breaking Changes

    :nut_and_bolt: Other

    ... (truncated)

    Changelog

    Sourced from mocha's changelog.

    10.2.0 / 2022-12-11

    :tada: Enhancements

    • #4945: API: add possibility to decorate ESM name before import (@​j0tunn)

    :bug: Fixes

    :book: Documentation

    10.1.0 / 2022-10-16

    :tada: Enhancements

    :nut_and_bolt: Other

    10.0.0 / 2022-05-01

    :boom: Breaking Changes

    :nut_and_bolt: Other

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • accept-language as part of the response skipped in the success response

    accept-language as part of the response skipped in the success response

    Reproduction

    Steps to reproduce the behavior:

    1. in the response of any api called should have accept-language as key for example response data : {key1: "key1data", "accept_language": "accept_language_data"}
    2. if you use node-fetch this "accept_language" get's removed from the response. This seems to be really weird

    Expected behavior The key should be returned as part of the response

    Hack / Temp Solutions: Added a header key 'Accept-Language' to the headers which resolves this issue

    Screenshots

    Your Environment

    | software | version | ---------------- | ------- | node-fetch | 2.6.7 | node | v14.17.6 | npm | 6.14.15 | Operating System |

    Additional context

    bug 
    opened by abdullasulaiman 0
  • [#1576] Fixes unexpected premature close on chunked responses

    [#1576] Fixes unexpected premature close on chunked responses

    Purpose

    Fixes #1576 (unexpected premature close errors on chunked responses)

    Changes

    It corrects a false assumption about split of the 'LAST CHUNK' marker between the previous and current buffer. The new solution concatenates last bytes of the previous buffer with all bytes from the current buffer (if that holds less then 5 bytes) and does the check on that.

    Additional information


    • [ ] I updated readme
    • [ ] I added unit test(s)

    • fix #1576
    opened by Treverix 1
Releases(v3.3.0)
  • v3.3.0(Nov 10, 2022)

  • v3.2.10(Jul 31, 2022)

  • v3.2.9(Jul 18, 2022)

  • v3.2.8(Jul 12, 2022)

  • v3.2.7(Jul 11, 2022)

  • v3.2.6(Jun 9, 2022)

  • v3.2.5(Jun 1, 2022)

  • v3.2.4(Apr 28, 2022)

  • v3.2.3(Mar 11, 2022)

  • v3.2.2(Mar 7, 2022)

  • v3.2.1(Mar 1, 2022)

  • v4.0.0-beta.4(Jan 27, 2022)

  • v4.0.0-beta.3(Jan 27, 2022)

  • v4.0.0-beta.2(Jan 27, 2022)

  • v4.0.0-beta.1(Jan 27, 2022)

  • v3.2.0(Jan 20, 2022)

  • v3.1.1(Jan 16, 2022)

    Security patch release

    Recommended to upgrade, to not leak sensitive cookie and authentication header information to 3th party host while a redirect occurred

    What's Changed

    • core: update fetch-blob by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1371
    • docs: Fix typo around sending a file by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1381
    • core: (http.request): Cast URL to string before sending it to NodeJS core by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1378
    • core: handle errors from the request body stream by @mdmitry01 in https://github.com/node-fetch/node-fetch/pull/1392
    • core: Better handle wrong redirect header in a response by @tasinet in https://github.com/node-fetch/node-fetch/pull/1387
    • core: Don't use buffer to make a blob by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1402
    • docs: update readme for TS @types/node-fetch by @adamellsworth in https://github.com/node-fetch/node-fetch/pull/1405
    • core: Fix logical operator priority to disallow GET/HEAD with non-empty body by @maxshirshin in https://github.com/node-fetch/node-fetch/pull/1369
    • core: Don't use global buffer by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1422
    • ci: fix main branch by @dnalborczyk in https://github.com/node-fetch/node-fetch/pull/1429
    • core: use more node: protocol imports by @dnalborczyk in https://github.com/node-fetch/node-fetch/pull/1428
    • core: Warn when using data by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1421
    • docs: Create SECURITY.md by @JamieSlome in https://github.com/node-fetch/node-fetch/pull/1445
    • core: don't forward secure headers to 3th party by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1449

    New Contributors

    • @mdmitry01 made their first contribution in https://github.com/node-fetch/node-fetch/pull/1392
    • @tasinet made their first contribution in https://github.com/node-fetch/node-fetch/pull/1387
    • @adamellsworth made their first contribution in https://github.com/node-fetch/node-fetch/pull/1405
    • @maxshirshin made their first contribution in https://github.com/node-fetch/node-fetch/pull/1369
    • @JamieSlome made their first contribution in https://github.com/node-fetch/node-fetch/pull/1445

    Full Changelog: https://github.com/node-fetch/node-fetch/compare/v3.1.0...v3.1.1

    Source code(tar.gz)
    Source code(zip)
  • v2.6.7(Jan 16, 2022)

    Security patch release

    Recommended to upgrade, to not leak sensitive cookie and authentication header information to 3th party host while a redirect occurred

    What's Changed

    • fix: don't forward secure headers to 3th party by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1453

    Full Changelog: https://github.com/node-fetch/node-fetch/compare/v2.6.6...v2.6.7

    Source code(tar.gz)
    Source code(zip)
  • v3.1.0(Nov 8, 2021)

    What's Changed

    • fix(Body): Discourage form-data and buffer() by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1212
    • fix: Pass url string to http.request by @serverwentdown in https://github.com/node-fetch/node-fetch/pull/1268
    • Fix octocat image link by @lakuapik in https://github.com/node-fetch/node-fetch/pull/1281
    • fix(Body.body): Normalize Body.body into a node:stream by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/924
    • docs(Headers): Add default Host request header to README.md file by @robertoaceves in https://github.com/node-fetch/node-fetch/pull/1316
    • Update CHANGELOG.md by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1292
    • Add highWaterMark to cloned properties by @davesidious in https://github.com/node-fetch/node-fetch/pull/1162
    • Update README.md to fix HTTPResponseError by @thedanfernandez in https://github.com/node-fetch/node-fetch/pull/1135
    • docs: switch url to URL by @dhritzkiv in https://github.com/node-fetch/node-fetch/pull/1318
    • fix(types): declare buffer() deprecated by @dnalborczyk in https://github.com/node-fetch/node-fetch/pull/1345
    • chore: fix lint by @dnalborczyk in https://github.com/node-fetch/node-fetch/pull/1348
    • refactor: use node: prefix for imports by @dnalborczyk in https://github.com/node-fetch/node-fetch/pull/1346
    • Bump data-uri-to-buffer from 3.0.1 to 4.0.0 by @dependabot in https://github.com/node-fetch/node-fetch/pull/1319
    • Bump mocha from 8.4.0 to 9.1.3 by @dependabot in https://github.com/node-fetch/node-fetch/pull/1339
    • Referrer and Referrer Policy by @tekwiz in https://github.com/node-fetch/node-fetch/pull/1057
    • Add typing for Response.redirect(url, status) by @c-w in https://github.com/node-fetch/node-fetch/pull/1169
    • chore: Correct stuff in README.md by @Jiralite in https://github.com/node-fetch/node-fetch/pull/1361
    • docs: Improve clarity of "Loading and configuring" by @serverwentdown in https://github.com/node-fetch/node-fetch/pull/1323
    • feat(Body): Added support for BodyMixin.formData() and constructing bodies with FormData by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1314
    • template: Make PR template more task oriented by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1224
    • docs: Update code examples by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1365

    New Contributors

    • @serverwentdown made their first contribution in https://github.com/node-fetch/node-fetch/pull/1268
    • @lakuapik made their first contribution in https://github.com/node-fetch/node-fetch/pull/1281
    • @robertoaceves made their first contribution in https://github.com/node-fetch/node-fetch/pull/1316
    • @davesidious made their first contribution in https://github.com/node-fetch/node-fetch/pull/1162
    • @thedanfernandez made their first contribution in https://github.com/node-fetch/node-fetch/pull/1135
    • @dhritzkiv made their first contribution in https://github.com/node-fetch/node-fetch/pull/1318
    • @dnalborczyk made their first contribution in https://github.com/node-fetch/node-fetch/pull/1345
    • @dependabot made their first contribution in https://github.com/node-fetch/node-fetch/pull/1319
    • @c-w made their first contribution in https://github.com/node-fetch/node-fetch/pull/1169

    Full Changelog: https://github.com/node-fetch/node-fetch/compare/v3.0.0...v3.1.0

    Source code(tar.gz)
    Source code(zip)
  • v2.6.6(Oct 31, 2021)

    What's Changed

    • fix(URL): prefer built in URL version when available and fallback to whatwg by @jimmywarting in https://github.com/node-fetch/node-fetch/pull/1352

    Full Changelog: https://github.com/node-fetch/node-fetch/compare/v2.6.5...v2.6.6

    Source code(tar.gz)
    Source code(zip)
  • v2.6.2(Sep 7, 2021)

  • v3.0.0(Aug 31, 2021)

  • v3.0.0-beta.10(Jul 19, 2021)

    This package is now a ESM only package. To import fetch you either have to use

    import fetch from 'node-fetch';
    
    // Or if you are still using commonjs or want to lazy
    // import fetch then the async import works fine
    import('node-fetch') 
    

    See CHANGELOG for details.

    Source code(tar.gz)
    Source code(zip)
  • v3.0.0-beta.9(Sep 5, 2020)

  • v2.6.1(Sep 5, 2020)

  • v3.0.0-beta.8(Aug 10, 2020)

  • v3.0.0-beta.7(Jun 11, 2020)

  • v3.0.0-beta.6-exportfix(May 25, 2020)

  • v3.0.0-beta.6(May 25, 2020)

  • v3.0.0-beta.5(Apr 22, 2020)

Owner
Node Fetch
A light-weight module that brings Fetch API to Node.js
Node Fetch
A window.fetch JavaScript polyfill.

window.fetch polyfill The fetch() function is a Promise-based mechanism for programmatically making web requests in the browser. This project is a pol

GitHub 25.6k Jan 4, 2023
A tiny Node.js module for retrieving a request's Details (ip,os,browser)

request-details A tiny Node.js module for retrieving a request's Details (ip,os,browser) ⌨️ Installation npm install request-details ⚙️ Usage const Re

sajjad MrX 14 Aug 20, 2022
Run Node.js on Android by rewrite Node.js in Java

node-android Run Node.js on Android by rewrite Node.js in Java with the compatible API. third-party: libuvpp, libuv-java JNI code by Oracle. Build Clo

AppNet.Link 614 Nov 15, 2022
Promise based HTTP client for the browser and node.js

axios Promise based HTTP client for the browser and node.js New axios docs website: click here Table of Contents Features Browser Support Installing E

axios 98k Dec 31, 2022
Ajax for Node.js and browsers (JS HTTP client)

superagent Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features T

Sloth 16.2k Jan 1, 2023
A full-featured http proxy for node.js

node-http-proxy node-http-proxy is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as

http ... PARTY! 13.1k Jan 3, 2023
HTTP server mocking and expectations library for Node.js

Nock HTTP server mocking and expectations library for Node.js Nock can be used to test modules that perform HTTP requests in isolation. For instance,

Nock 11.9k Jan 3, 2023
🌐 Human-friendly and powerful HTTP request library for Node.js

Sindre's open source work is supported by the community. Special thanks to: Human-friendly and powerful HTTP request library for Node.js Moving from R

Sindre Sorhus 12.5k Jan 9, 2023
SPDY server on Node.js

SPDY Server for node.js With this module you can create HTTP2 / SPDY servers in node.js with natural http module interface and fallback to regular htt

SPDY & HTTP2 in JavaScript 2.8k Jan 4, 2023
libcurl bindings for Node.js

node-libcurl The fastest URL transfer library for Node.js. libcurl bindings for Node.js. libcurl official description: libcurl is a free and easy-to-u

Jonathan Cardoso 565 Jan 2, 2023
Full-featured, middleware-oriented, programmatic HTTP and WebSocket proxy for node.js

rocky A multipurpose, full-featured, middleware-oriented and hackable HTTP/S and WebSocket proxy with powerful built-in features such as versatile rou

Tom 370 Nov 24, 2022
Simplifies node HTTP request making.

Requestify - Simplifies node HTTP request making. Requestify is a super easy to use and extendable HTTP client for nodeJS + it supports cache (-:. Ins

Ran Mizrahi 222 Nov 28, 2022
A fully-featured Node.js REST client built for ease-of-use and resilience

flashheart A fully-featured Node.js REST client built for ease-of-use and resilience flashheart is built on http-transport to provide everything you n

BBC 118 Jun 21, 2022
Run HTTP over UDP with Node.js

nodejs-httpp - Run HTTP over UDP based transport and Bring Web in Peer or P2P styles main js modules: udt.js, httpp.js, udts.js and httpps.js, that's

AppNet.Link 142 Aug 2, 2022
一个基于node.js,express,socket.io的websocket非常棒的聊天室,代码简单很适合新手. A very nice websocket chat room based on node.js, express, socket.io. the code is simple, very suitable for novices

来来往下看,虽然教程又臭又长但是一步步地保姆式教学很简单的,毕竟我是真菜鸟嘛,当然什么都往细了说╮(╯_╰)╭ 一、使用方法 该教程内容所有指令都为Linux CentOS 7.x环境下指令,其他平台请您自行查询(⊙x⊙;) 1.下载node.js并下载Sakura_Chat_Room node.j

樱樱怪 10 Jul 21, 2022
node

第一步 安装 node node版本须大于14 安装地址http://nodejs.cn/安装页面上的版本即可 下载对应你的系统的安装包 打开安装包,一直下一步到安装完成即可 填入你的cookie inTimeActive 和 longActive 里面的jdCookie.js填入你的cookie

null 6 Feb 17, 2022
QBasic compiler that runs on node.js

QBasic.js QBasic.js allows you to use qb.js inside node projects. Example CLI $ npx qbasic --source=filePath.bas index.js const { compileFile } = requ

Andromeda 3 Oct 24, 2022
Trying to reduce the search time, the objective of this repository is accumulate as many useful code snippets for Node.Js in the real world as possible

Useful Node.Js codes Trying to reduce the search time, the objective of this repository is accumulate as many useful code snippets for Node.Js in the

Juninho 6 Mar 28, 2022
Very very very powerful, extensible http client for both node.js and browser.

ES-Fetch-API 中文 | English Very very very powerful, extensible http client for both node.js and browser. Why should you use ES-Fetch API? Still using a

null 17 Dec 12, 2022