I'm trying to call the Pagespeed Insights API from an AWS Lambda to get back the results.
The lambda is running Node 18 but still unable to get fetch()
to work.
It will show "inside the try about to fetch" in Cloudwatch but nothing after.
In my Lambda console, there is a warning that says fetch is not defined, please fix or add global fetch
. My timeout is 2 minutes and the API call only takes a max 20 second to return a response in the browser.
Any help would be appreciated.
Code:
try {
console.log("inside the try about to fetch", url)
const response = await fetch(url);
console.log("response", response)
const contentType = response.headers.get("content-type");
console.log("response content type", contentType)
if (!contentType || !contentType.includes("application/json")) {
throw new TypeError("Oops, we haven't got JSON!");
}
const jsonData = await response.json();
console.log("json data response", jsonData)
} catch (error) {
console.error("Error:", error);
return
}
I'm trying to call the Pagespeed Insights API from an AWS Lambda to get back the results.
The lambda is running Node 18 but still unable to get fetch()
to work.
It will show "inside the try about to fetch" in Cloudwatch but nothing after.
In my Lambda console, there is a warning that says fetch is not defined, please fix or add global fetch
. My timeout is 2 minutes and the API call only takes a max 20 second to return a response in the browser.
Any help would be appreciated.
Code:
try {
console.log("inside the try about to fetch", url)
const response = await fetch(url);
console.log("response", response)
const contentType = response.headers.get("content-type");
console.log("response content type", contentType)
if (!contentType || !contentType.includes("application/json")) {
throw new TypeError("Oops, we haven't got JSON!");
}
const jsonData = await response.json();
console.log("json data response", jsonData)
} catch (error) {
console.error("Error:", error);
return
}
Share
Improve this question
asked May 17, 2023 at 14:16
Trey CopelandTrey Copeland
3,5277 gold badges31 silver badges50 bronze badges
1
- I encountered the error in the Lambda console but it should still work as long as you are using Node 18.x. – CodeEngie Commented Oct 13, 2023 at 19:31
2 Answers
Reset to default 5I had the same issue and adding global fetch to the lambda solved the problem. Simply add this line to the top of your js file where you're using fetch
/* global fetch */
Give this a go its similar to the code I use modeled with your sample code.
exports const handler = async (event) {
try {
const response = await fetch(url);
if (!response.ok) {
new Error(`Oops we haven't got JSON: ${response.status}`);
}
const jsonData = await response.json();
console.log('json data response', jsonData);
} catch (error) {
console.log(`Error: ${error}`);
}
}