Isomorphic WHATWG Fetch API, for Node & Browserify

Overview

isomorphic-fetch Build Status

Fetch for node and Browserify. Built on top of GitHub's WHATWG Fetch polyfill.

Warnings

  • This adds fetch as a global so that its API is consistent between client and server.

For ease-of-maintenance and backward-compatibility reasons, this library will always be a polyfill. As a "safe" alternative, which does not modify the global, consider fetch-ponyfill.

Why Use Isomorphic Fetch

The Fetch API is currently not implemented consistently across browsers. This module will enable you to use fetch in your Node code in a cross-browser compliant fashion. The Fetch API is part of the Web platform API defined by the standards bodies WHATWG and W3C.

Installation

NPM

npm install --save isomorphic-fetch

Bower

bower install --save isomorphic-fetch

Usage

require('isomorphic-fetch');

fetch('//offline-news-api.herokuapp.com/stories')
	.then(function(response) {
		if (response.status >= 400) {
			throw new Error("Bad response from server");
		}
		return response.json();
	})
	.then(function(stories) {
		console.log(stories);
	});

License

All open source code released by FT Labs is licenced under the MIT licence. Based on the fine work by jxck.

Alternatives

Comments
  • json body not posted

    json body not posted

    Hi. I'm trying to make a post request with json in the body included. The request is indeed a post request but the json data isn't posted.

    Here is an example:

    fetch("http://127.0.0.1:8080/v1.0/users", {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            email: 'foo',
            pass: 'bar'
          })
        }).then(response => console.log(response))
    

    Results in the following request headers:

    POST /v1.0/users HTTP/1.1 Host: 127.0.0.1:8080 Connection: keep-alive Content-Length: 28 accept: application/json Origin: http://127.0.0.1:3000 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36 content-type: application/json DNT: 1 Referer: http://127.0.0.1:3000/registration Accept-Encoding: gzip, deflate Accept-Language: nl,en-US;q=0.8,en;q=0.6

    There is no data posted. Can anyone point me in the right direction? Thanks!

    opened by Roconda 48
  • Request Method: OPTIONS

    Request Method: OPTIONS

    I'm trying to make a POST request but I'm still sending OPTIONS as a 'Request Method'.

    Example:

    import fetch from 'isomorphic-fetch'
    
    fetch('http://localhost:3000/api/v1/sign_in', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: {
          login: 'test'
        }
    })
    

    In Chrome, I can see: Remote Address:127.0.0.1:3000 Request URL:http://localhost:3000/api/v1/sign_in Request Method:OPTIONS Status Code:404 Not Found

    Thanks in advance.

    opened by 14113 13
  • Tag a new version with the security fix

    Tag a new version with the security fix

    I see that you updated your node-fetch dependency a couple of hours ago to fix a minor security vulnerability. I'm here looking for an updated version because I received the same vulnerability notification from :octocat:... So I'm probably not the only one looking for a new version of isomorphic-fetch that I can slap into my package.json to make the alert go away. :)

    opened by atuttle 11
  • Update node-fetch to `^2.0.0` (major change)

    Update node-fetch to `^2.0.0` (major change)

    This will change the behavior of isomorphic-fetch if imported in a Node.js environment. The actual major changes can be found in the 2.0.0 release notes of node-fetch. See: https://github.com/bitinn/node-fetch/blob/master/CHANGELOG.md#v200

    Overall, this should increase the usefulness of isomorphic-fetch by a lot since version 2 aligns the implementation with the spec for a lot of issues. For instance, I expect this to fix:

    opened by leoselig 10
  • Prevent Illegal invocation Error in webpack

    Prevent Illegal invocation Error in webpack

    I am using ES6 modules with webpack and I ran into an issue. My code was something like this:

    import fetch from 'isomorphic-fetch';
    
    fetch(url)
      // .then do stuff
    

    which raised an Illegal invocation Error. This is the same error that happens when you do something like this:

    log = console.log
    log('hello'); // Error
    

    I looked at the compiled code and it looked like this:

    var _fetch = __webpack_require__(10);
    var _fetch2 = _interopRequireWildcard(_fetch);
    
    _fetch2['default'](url);
    

    which is the problem because now the fetch function is called with a this value of the _fetch2 module. It is similar to doing the following:

    var obj = {myFetch: fetch};
    
    obj.myFetch(url); // Error
    

    So I just made sure that fetch was bound to the window object on importing. This of course assumes that Function.bind exists or was polyfilled.

    opened by rockymeza 10
  • Bump node-fetch from 1.7.3 to 2.6.1

    Bump node-fetch from 1.7.3 to 2.6.1

    Bumps node-fetch from 1.7.3 to 2.6.1.

    Release notes

    Sourced from node-fetch's releases.

    v2.6.1

    This is an important security release. It is strongly recommended to update as soon as possible.

    See CHANGELOG for details.

    v2.6.0

    See CHANGELOG.

    v2.5.0

    See CHANGELOG.

    v2.4.1

    See CHANGELOG.

    v2.4.0

    See CHANGELOG.

    v2.3.0

    See CHANGELOG.

    v2.2.1

    See CHANGELOG.

    Version 2.1.2

    • Fix: allow Body methods to work on ArrayBuffer-backed Body` objects
    • Fix: reject promise returned by Body methods when the accumulated Buffer exceeds the maximum size
    • Fix: support custom Host headers with any casing
    • Fix: support importing fetch() from TypeScript in browser.js
    • Fix: handle the redirect response body properly

    See CHANGELOG.

    Version 2.1.1

    See CHANGELOG.

    Fix packaging errors in version 2.1.0.

    Version 2.1.0

    See CHANGELOG:

    • Enhance: allow using ArrayBuffer as the body of a fetch() or Request
    • Fix: store HTTP headers of a Headers object internally with the given case, for compatibility with older servers that incorrectly treated header names in a case-sensitive manner
    • Fix: silently ignore invalid HTTP headers
    • Fix: handle HTTP redirect responses without a Location header just like non-redirect responses
    • Fix: include bodies when following a redirection when appropriate

    Version 2.0.0

    This is a major release. See upgrade guide on how to upgrade from v1.x, and the changelog for all changes.

    v2.0.0-alpha.9

    Changelog

    Sourced from node-fetch's changelog.

    v2.6.1

    This is an important security release. It is strongly recommended to update as soon as possible.

    • Fix: honor the size option after following a redirect.

    v2.6.0

    • Enhance: options.agent, it now accepts a function that returns custom http(s).Agent instance based on current URL, see readme for more information.
    • Fix: incorrect Content-Length was returned for stream body in 2.5.0 release; note that node-fetch doesn't calculate content length for stream body.
    • Fix: Response.url should return empty string instead of null by default.

    v2.5.0

    • Enhance: Response object now includes redirected property.
    • Enhance: fetch() now accepts third-party Blob implementation as body.
    • Other: disable package-lock.json generation as we never commit them.
    • Other: dev dependency update.
    • Other: readme update.

    v2.4.1

    • Fix: Blob import rule for node < 10, as Readable isn't a named export.

    v2.4.0

    • Enhance: added Brotli compression support (using node's zlib).
    • Enhance: updated Blob implementation per spec.
    • Fix: set content type automatically for URLSearchParams.
    • Fix: Headers now reject empty header names.
    • Fix: test cases, as node 12+ no longer accepts invalid header response.

    v2.3.0

    • Enhance: added AbortSignal support, with README example.
    • Enhance: handle invalid Location header during redirect by rejecting them explicitly with FetchError.
    • Fix: update browser.js to support react-native environment, where self isn't available globally.

    v2.2.1

    • Fix: compress flag shouldn't overwrite existing Accept-Encoding header.
    • Fix: multiple import rules, where PassThrough etc. doesn't have a named export when using node <10 and --experimental-modules flag.
    • Other: Better README.

    v2.2.0

    • Enhance: Support all ArrayBuffer view types
    • Enhance: Support Web Workers
    • Enhance: Support Node.js' --experimental-modules mode; deprecate .es.js file
    • Fix: Add __esModule property to the exports object
    Commits
    • b5e2e41 update version number
    • 2358a6c Honor the size option after following a redirect and revert data uri support
    • 8c197f8 docs: Fix typos and grammatical errors in README.md (#686)
    • 1e99050 fix: Change error message thrown with redirect mode set to error (#653)
    • 244e6f6 docs: Show backers in README
    • 6a5d192 fix: Properly parse meta tag when parameters are reversed (#682)
    • 47a24a0 chore: Add opencollective badge
    • 7b13662 chore: Add funding link
    • 5535c2e fix: Check for global.fetch before binding it (#674)
    • 1d5778a docs: Add Discord badge
    • Additional commits viewable in compare view
    Maintainer changes

    This version was pushed to npm by akepinski, a new releaser for node-fetch since your current version.


    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)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 9
  • Updated dependencies to the latest versions

    Updated dependencies to the latest versions

    All tests pass, what else can I say?

    packages.json

     node-fetch     1.0.1  →   1.3.3
     whatwg-fetch  0.10.0  →  0.11.0
     jshint          2.5.11  →  2.9.1
     mocha            2.1.0  →  2.3.4
     npm-prepublish   1.0.2  →  1.2.1
    

    bower.json

    "dependencies": {
        "fetch": "github/fetch#>=0.11.0"
      }
    
    opened by nightwolfz 8
  • Question: how to a POST with form-data correctly

    Question: how to a POST with form-data correctly

    Hi,

    So my question is how I would implement the following (with request) using isomorphic-fetch

    var options = {
        url: authUrlRoot + 'auth',
        followRedirect: false,
        form: {
          client_id: config.APP_KEY,
          redirect_uri: config.REDIRECT_URL,
          response_type: "code"
        }
      };
    
      request.post(options, function(error, httpResponse, body){
        // Do something here..
      });
    

    I've tried something like

    var FormData = require('form-data');
    var form = new FormData();
    form.append('client_id', config.APP_KEY);
    form.append('redirect_url', config.REDIRECT_URL);
    form.append('response_type', 'code');
    fetch(authUrlRoot + 'auth', { method: 'POST', body: form })
        .then(function(response) {
            if (response.status >= 400) {
                throw new Error("Bad response from server");
            }
            return response.json();
        })
        .then(function(data) {
            console.log(data);
        });
    

    But that gives me "Bad response from server" - status code is 400 Bad request. I might be totally blind, but I cannot seem to figure out what is missing?

    opened by dgsunesen 8
  • Which files need to be hosted on cdnjs?

    Which files need to be hosted on cdnjs?

    Hi, I'd like to host your library, isomorphic-fetch on cdnjs — It is one of the most famous free and public web front-end CDN services which is used by ~1,143,000 websites worldwide.

    There are three files which seem relevant to me in your repository:

    fetch-bower.js
    fetch-npm-browserify.js
    fetch-npm-node.js
    

    Which files out of the ones listed above will work in a browser and let developers use your library directly? Also, please let me know if there are any other files that should be hosted.

    opened by dakshshah96 7
  • Calling response.json() when processing an error request (40x) returns a promise, not the data in the body

    Calling response.json() when processing an error request (40x) returns a promise, not the data in the body

    When I send an error from my restful api back to the server, I want to include a message. Flask has nice support for this and I can say:

    if not token:
        return {‘message’: ‘Missing token’}, 401
    

    I can see the data in the body of the response and content-type is application/json.

    In my app I’m using isomorphic-fetch and I’m saying:

    fetch('...url...')
        .then(response => {
            if (!response.ok) {
                const data = response.json();
                ...
    

    Trouble is, data always comes out being an unresolved promise. If I poke around inside using the debugger I can see my data (it’s in [[PromiseValue]]) but I can’t get it. I've tried calling .then() on it to try to resolve it but that just seems to generate another Promise.

    How is this supposed to work? This code works fine when the response isn't an error.

    opened by bggolding 6
  • Error: Can't find variable: self

    Error: Can't find variable: self

    Hello.

    I am using redux-api-middleware which is using version 2.2.1 of isomorphic-fetch. I am experiencing an error where self is undefined in React Native, which is a problem with this version of isomorphic-fetch. Most issues I have seen regarding this issue have been closed, but I feel that this is a fairly common issue and I have not been able to find a good solution. I'd love to work together, with a maintainer or anyone else having this problem, to solve it.

    Thank you for reading and for your work on this library.

    The error seems to be coming from this file:

    image

    Here is the stack trace:

    image

    opened by Connorelsea 6
  • How to access the referer using isomorphic fetch library? An example would help!

    How to access the referer using isomorphic fetch library? An example would help!

    I am trying to access the referer in a universal application and since referer is a Dom property I cannot access it in both SSR and CSR so I am using this but am unable to figure out on how to access the referer

    opened by meridian12034 0
  • Interceptors

    Interceptors

    Hi, First of all thank you for awesome library

    I am working on a nextjs project, which has both client and server(node). We use this library thoughout our project. We are intending to use interceptor so as to log out response under one single place and send to insights library. Any possible way or module you could suggest which would do the same?

    Thanks in advance.

    opened by Phalguna2125 0
  • Found a possible security concern

    Found a possible security concern

    Hey there!

    I belong to an open source security research community, and a member (@ranjit-git) has found an issue, but doesn’t know the best way to disclose it.

    If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

    Thank you for your consideration, and I look forward to hearing from you!

    (cc @huntr-helper)

    opened by JamieSlome 2
  • Security risk

    Security risk

    Affected files: isomorphic-fetch/node_modules/node-fetch/lib/index.js 1327: headers.set('location', resolve_url(request.url, headers.get('location')));

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 827: set(name, value) {

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 828: this[MAP][sanitizeName(name)] = [sanitizeValue(value)];

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 702: function sanitizeValue(value) {

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 704: if (checkInvalidHeaderChar(value)) {

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 670: function checkInvalidHeaderChar(val) {

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 673: var c = val.charCodeAt(0);

    isomorphic-fetch/node_modules/node-fetch/lib/index.js 681: for (var i = 3; i < val.length; ++i) {

    Risks: An attacker could provide a very high loop iteration count, causing the loop to go on for prolonged periods of time, potentially causing the application to stop responding. Additionally, if the operation inside the loop is tied to some exhaustible functionality, it may cause bloat elsewhere; For example - if file writes occur inside the loop, then an attacker can cause that file to bloat by simply engaging this file writing capability a very high amount of times.

    The application relied on a user-provided value to determine the number of iterations performed by a loop, without enforcing a limited range for this value.

    Affected files: isomorphic-fetch/node_modules/node-fetch/test/test.js 43: url = 'http://example.com/';

    isomorphic-fetch/node_modules/node-fetch/test/test.js 44: var p = fetch(url)

    isomorphic-fetch/node_modules/node-fetch/test/test.js 50: url = 'http://example.com/';

    isomorphic-fetch/node_modules/node-fetch/test/test.js 54: expect(fetch(url)).to.not.be.an.instanceof(bluebird);

    isomorphic-fetch/node_modules/node-fetch/test/test.js 50: url = 'http://example.com/';

    isomorphic-fetch/node_modules/node-fetch/test/test.js 53: expect(fetch(url)).to.be.an.instanceof(then);

    isomorphic-fetch/node_modules/node-fetch/test/test.js 90: url = 'http://localhost:50000/';

    isomorphic-fetch/node_modules/node-fetch/test/test.js 91: return expect(fetch(url)).to.eventually.be.rejected

    isomorphic-fetch/node_modules/node-fetch/test/test.js 417: url = 'http://domain.invalid';

    isomorphic-fetch/node_modules/node-fetch/test/test.js 418: return expect(fetch(url)).to.eventually.be.rejected

    Risks: Sending data over the network is inherently risky, unless the communication channel is protected using a secured protocol. This is especially true for mobile devices that are often connected to non-secure networks and untrusted hotspots. An attacker can easily eavesdrop on the information being sent over the air, and even manipulate the data in some scenarios.

    Thus, an attacker could steal any personal or secret data sent over unencrypted HTTP, such as passwords, credit card details, social security numbers, and other forms of PII (Personally Identifiable Information), leading to identity theft and other forms of fraud. Additionally, it may be possible for an active attacker to alter the data and inject false or malicious data, causing further damage to the application server or the client app.

    The app handles various forms of sensitive data, and communicates with the remote application server. However, the app connects using an ""http://"" URL, which will cause the underlying channel to use straight HTTP, without securing it with SSL/TLS.

    opened by KennyGoi 0
Releases(v2.1.1)
Owner
Matt Andrews
Software engineer making apps – that aren’t apps – and more at the FT. 会说汉语.
Matt Andrews
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
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
Async node.js implementation of the UDP Minecraft Server Query Protocol and TCP Minecraft Server List Ping Protocol

?? Mc Server Status Async node.js implementation of the UDP Minecraft Server Query Protocol and TCP Minecraft Server List Ping Protocol. Also availabl

Daniel 5 Nov 10, 2022