使用SerpAPI调用Google Lens时出现AbortSignal未定义错误求助
解决Node.js中ReferenceError: AbortSignal is not defined问题
问题描述
本地运行调用SerpAPI的Node.js脚本时,无论使用官网示例代码还是自定义代码,均触发以下错误:
signal: AbortSignal.timeout(timeout),
^
ReferenceError: AbortSignal is not defined
但相同代码在Replit上可正常运行,推测为本地环境问题。
相关代码
import { getJson } from "serpapi"; const params = { url: "https://i.imgur.com/HBrB8p0.png", api_key: "{xxx}" }; // Show result as JSON const response = await getJson("google_lens", params); console.log(response["visual_matches"]);
package.json依赖信息
{ "name": "cheerio", "version": "1.0.0", "description": "", "main": "index.js", "type": "module", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "@google-cloud/vision": "^3.1.1", "axios": "^1.3.2", "cheerio": "^1.0.0-rc.12", "jimp": "^0.22.4", "node-fetch": "^3.3.0", "openai": "^3.1.0", "serpapi": "^1.1.0" } }
原因分析
AbortSignal是Node.js 16.14.0及以上版本(或18.0.0+)才内置的API,本地Node.js版本低于该阈值时,就会出现未定义的错误。Replit使用的是较新版本的Node.js,因此可以正常运行。
解决方案
- 检查本地Node.js版本:执行命令
node -v查看当前版本 - 升级Node.js版本(推荐):
- 若使用nvm,执行
nvm install --lts安装长期支持版,再用nvm use --lts切换到该版本 - 直接下载对应版本的安装包进行安装
- 若使用nvm,执行
- 临时兼容方案(不推荐):安装
abort-controller包,在代码顶部添加以下内容:import AbortController from 'abort-controller'; globalThis.AbortController = AbortController; globalThis.AbortSignal = AbortController.signal;
内容的提问来源于stack exchange,提问作者Zach Wadzinski
相关产品推荐
相关产品推荐

