AWS Lambda Node 18:未定义提取,请修复或添加全局提取

Tre*_*and 6 javascript amazon-web-services node.js

我正在尝试从 AWS Lambda 调用 Pagespeed Insights API 以获取结果。lambda 正在运行 Node 18,但仍然无法开始fetch()工作。

它会在 Cloudwatch 中显示“在尝试获取中”,但之后什么也没有。

在我的 Lambda 控制台中,有一条警告称fetch is not defined, please fix or add global fetch. 我的超时时间是 2 分钟,API 调用最多只需要 20 秒即可在浏览器中返回响应。

任何帮助,将不胜感激。

代码

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
      }
Run Code Online (Sandbox Code Playgroud)

Cod*_*gie 0

尝试一下,它与我使用的与您的示例代码建模的代码类似。

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}`);
}
Run Code Online (Sandbox Code Playgroud)

}