serverless-nodejs-starter icon indicating copy to clipboard operation
serverless-nodejs-starter copied to clipboard

fetch Not Supported When Deployed

Open dougmacklin opened this issue 8 years ago • 3 comments

Hi there, thanks in advance for this very helpful repo. I noticed that if I attempt to use fetch, it will work locally, but fail when deployed. Is this to be expected? I assumed ES7 support covered fetch, however maybe that was a dumb assumption.

Steps to reproduce:

  1. Follow this repo's installation instructions
  2. In handler.js, add the following code to attempt fetching from the google maps API, above the const reponse = ... line
try {
  const weather = await fetch('https://maps.googleapis.com/maps/api/geocode/json?address=San%Francisco');
  console.log(JSON.stringify(weather, undefined, 2));
} catch (err) {
  console.error('could not fetch');
}
  1. Invoke the function locally to see that it works: serverless webpack invoke -f hello -l
  2. Deploy the service: serverless deploy -v
  3. Invoke the function and notice the error in the logs: serverless invoke -f hello -l

dougmacklin avatar Jul 17 '17 14:07 dougmacklin

@dougmacklin Thanks for the really detailed report. You are right it is a little weird that fetch isn't in Babel. Here is one of the Babel maintainers talking about it as well - https://stackoverflow.com/questions/36484156/es6-fetch-is-undefined/44217058#44217058

The recommendation (and this is what Create React App does on the front end as well) is to use https://github.com/github/fetch.

It's pretty straightforward to use. If it works then you can try adding it to your Webpack config directly and let me know how it goes.

jayair avatar Jul 18 '17 17:07 jayair

Thanks @jayair, I ended up using this polyfill for node, as the github one seems to be for front end only: https://github.com/bitinn/node-fetch

It's working as expected now!

dougmacklin avatar Jul 18 '17 17:07 dougmacklin

@dougmacklin yeah that makes sense.

jayair avatar Jul 18 '17 18:07 jayair