Astro中使用@vercel/og时出现TypeError: fetch failed错误
使用@vercel/og生成OG图片时本地运行报错的解决办法
问题详情
我在Astro应用中尝试用@vercel/og包创建API路由生成Open Graph图片,基本复制了Vercel的框架无关示例代码:
// api/og.ts import { ImageResponse } from "@vercel/og"; export const config = { runtime: "edge", }; export default function () { return new ImageResponse( ( <div style={{ fontSize: 128, background: "white", width: "100%", height: "100%", display: "flex", textAlign: "center", alignItems: "center", justifyContent: "center", }} > Hello world! </div> ), { width: 1200, height: 600, } ); }
运行vercel dev后访问http://localhost:3000/api/og,出现500错误提示“This Serverless Function has crashed”,控制台报错如下:
TypeError: fetch failed at Object.processResponse (evalmachine.<anonymous>:7941:27) at evalmachine.<anonymous>:8271:42 at node:internal/process/task_queues:140:7 at AsyncResource.runInAsyncScope (node:async_hooks:204:9) at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8) { cause: Error: not implemented... yet... at makeNetworkError (evalmachine.<anonymous>:6735:35) at schemeFetch (evalmachine.<anonymous>:8238:18) at evalmachine.<anonymous>:8115:26 at mainFetch (evalmachine.<anonymous>:8134:11) at fetching (evalmachine.<anonymous>:8088:7) at Agent2.fetch (evalmachine.<anonymous>:7953:20) at fetch (evalmachine.<anonymous>:11747:40) at evalmachine.<anonymous>:18606:20 at Script.runInContext (node:vm:141:12) at runInContext (node:vm:291:6) { [cause]: undefined } }
更新发现
进一步测试后发现,问题由导入语句本身导致。即使只保留导入,返回普通Response也会报错:
import { ImageResponse } from "@vercel/og"; export const config = { runtime: "edge", }; export default function () { return new Response("Hello world!"); }
但移除import { ImageResponse } from "@vercel/og";后,函数就能正常运行。推测问题和本地Edge Runtime有关,但不清楚具体修复方法。
解决办法
针对这个问题,有以下几种可行的解决方案:
升级Vercel CLI到最新版本:旧版本的
vercel dev对@vercel/og的本地支持存在缺陷,执行以下命令升级:npm install -g vercel@latest # 或使用pnpm pnpm add -g vercel@latest改用Astro官方OG生成工具:Astro提供了适配性更好的
@astrojs/og包,不需要依赖Vercel Edge Runtime的本地环境,更适合Astro项目。直接部署到Vercel线上测试:本地Edge Runtime存在部分未实现的功能,但部署到Vercel线上环境后,@vercel/og通常能正常运行,可以先部署验证功能是否正常。
检查Node.js版本:确保使用的Node.js版本符合@vercel/og的要求,建议使用Node.js 18及以上版本。
内容的提问来源于stack exchange,提问作者Axel Padilla
相关产品推荐
相关产品推荐

