AWS Lambda Node18中fetch未定义:调用Pagespeed Insights API失败求助
解决AWS Lambda Node.js 18中fetch未定义的问题
问题分析
Node.js 18原生支持fetch,但在AWS Lambda环境中仍出现fetch is not defined报错,且仅输出inside the try about to fetch日志,说明代码执行到fetch调用时触发同步错误,可能因环境配置或代码结构问题未进入catch块。
解决步骤
- 确认Lambda运行时版本:检查Lambda函数的运行时是否为Node.js 18.x(如18.20.3),避免误选旧版本(如16.x)。
- 确保handler为async函数:
await必须在async函数中使用,Lambda handler需定义为async函数,否则会触发语法错误导致代码中断。
具体修复方案
方案1:显式引入内置的undici fetch
Node.js 18的fetch基于undici实现,Lambda环境中可能需显式引入:
const { fetch } = require('undici'); exports.handler = async (event) => { const url = "你的Pagespeed Insights API地址"; 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); return { statusCode: 200, body: JSON.stringify(jsonData) }; } catch (error) { console.error("Error:", error); return { statusCode: 500, body: JSON.stringify({ error: error.message }) }; } };
方案2:使用node-fetch作为替代
如果内置fetch仍无法正常工作,可安装node-fetch包作为fallback:
- 本地安装依赖:
npm install node-fetch@2 - 在代码中引入并使用:
const fetch = require('node-fetch'); exports.handler = async (event) => { // 后续代码与上述示例一致 };
方案3:排查部署包冲突
若部署包中包含旧版本Node.js依赖,可能覆盖原生fetch。确保打包时仅包含必要依赖,或检查是否有第三方库修改了全局fetch变量。
内容的提问来源于stack exchange,提问作者Trey Copeland
相关产品推荐
相关产品推荐

