serverless-nodejs-starter
serverless-nodejs-starter copied to clipboard
fetch Not Supported When Deployed
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:
- Follow this repo's installation instructions
- 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');
}
- Invoke the function locally to see that it works:
serverless webpack invoke -f hello -l - Deploy the service:
serverless deploy -v - Invoke the function and notice the error in the logs:
serverless invoke -f hello -l
@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.
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 yeah that makes sense.