Esri / arcgis-rest-js

compact, modular JavaScript wrappers for the ArcGIS REST API
https://developers.arcgis.com/arcgis-rest-js/
Apache License 2.0
353 stars 119 forks source link

Trouble polyfill fetch in Node with typescript #666

Closed ajturner closed 3 years ago

ajturner commented 4 years ago

I'm attempting to build an express app with Node 11. I've added the following to my app.js while my arcgis-rest-js calls are made in various Util modules. I never directly call request - only using the geocoding and Portal module methods.

const fetch = require('node-fetch');
import * as RestRequest from '@esri/arcgis-rest-request';

// use node-fetch for each request instead of relying on a global
RestRequest.setDefaultRequestOptions({ fetch })

but I still get the error

UnhandledPromiseRejectionWarning: Error: `arcgis-rest-request` requires a `fetch` implementation and global variables for `Promise` and `FormData` to be present in the global scope. You are missing `fetch`, `FormData`. We recommend installing the `node-fetch`, `isomorphic-form-data` modules at the root of your application to add these to the global scope. See https://bit.ly/2KNwWaJ for more info.

@dbouwman @patrickarlt

patrickarlt commented 4 years ago

You also need a global for FormData which is why the error is being thrown. We don't allow you to pass in a FormData implementation like we do for fetch.

Aside from "don't pollute the global namespace" (this isn't the worst IMO) is there are a particular reason for not just going:

require("cross-fetch/polyfill");
require("isomorphic-form-data");

In your app.js like we recommend?

jf990 commented 4 years ago

I have it set like this, not sure if there's a difference, but I thought it avoided the global pollution (not sure I'm right about that). Also, I am using node 12. But I do not get the missing fetch error.

require("isomorphic-form-data");
const fetch = require("cross-fetch");
const { setDefaultRequestOptions } = require("@esri/arcgis-rest-request");

setDefaultRequestOptions({ fetch });
patrickarlt commented 3 years ago

This should be resolved with https://github.com/Esri/arcgis-rest-js/pull/911. At 4.0 we are going to bundle a new dependency on @esri/arcgis-rest-fetch which is cross-fetch without a global and without a browser polyfill. Everything will go to node-fetch under the hood for Node, native fetch for browsers and the TypeScript types should be correct. There will be no more custom fetch option.