Firebase Genkit配置HTTP代理失败问题求助
解决Firebase Genkit的模块警告与代理fetch失败问题
问题背景
使用Firebase Genkit时,已通过以下bash命令配置代理:
export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 all_proxy=socks5://127.0.0.1:7890
该配置在curl中可正常生效,但运行Node.js代码时出现fetch failed错误,同时触发模块类型警告。
1. 消除模块类型警告
根据错误提示,直接在项目根目录的package.json中添加"type": "module"字段,示例如下:
{ "type": "module", "dependencies": { "@genkit-ai/googleai": "^x.x.x", "genkit": "^x.x.x" } }
保存文件后重新运行脚本,即可消除模块类型解析警告。
2. 解决fetch失败(代理配置问题)
Node.js内置的fetch基于undici实现,默认不会读取系统代理环境变量,需手动配置:
方案一:代码中显式配置代理
- 先安装undici依赖:
npm install undici
- 修改代码,添加代理配置:
import { gemini20Flash, googleAI } from '@genkit-ai/googleai'; import { genkit } from 'genkit'; import { ProxyAgent } from 'undici'; // 初始化代理实例,替换为你的代理地址 const proxyAgent = new ProxyAgent('http://127.0.0.1:7890'); const ai = genkit({ plugins: [ googleAI({ clientConfig: { fetchOptions: { dispatcher: proxyAgent, }, }, }), ], model: gemini20Flash, }); async function main() { const { text } = await ai.generate('Hello, Gemini!'); console.log(text); } main();
方案二:使用实验性代理特性
Node.js v22提供了实验性的fetch代理支持,通过设置环境变量启用:
export NODE_OPTIONS='--experimental-fetch-proxy' export https_proxy=http://127.0.0.1:7890 http_proxy=http://127.0.0.1:7890 node ./test.js
此方案无需修改代码,但特性为实验性,后续版本可能有变动。
内容的提问来源于stack exchange,提问作者Yuchang Ke
相关产品推荐
相关产品推荐

