在Next.js API路由使用@axe-core/playwright时遇ERR_INVALID_FILE_URL_PATH错误
解决Next.js 15 API路由中使用@axe-core/playwright的"File URL path must be absolute"错误
问题根源
Next.js 15的App Router API路由默认启用边缘运行时,该环境限制了文件系统的直接访问权限。@axe-core/playwright内部会尝试读取本地的axe-core脚本文件,边缘环境的路径处理逻辑会导致它无法解析正确的绝对路径,从而抛出ERR_INVALID_FILE_URL_PATH错误。另外,新版本的@axe-core/playwright已不再推荐手动传入axeSource,但包结构变化导致旧方法失效。
解决方案
1. 切换到Node.js运行时
在API路由文件顶部添加配置,强制使用Node.js运行时,这样就能正常访问文件系统并运行Playwright:
export const runtime = 'nodejs';
2. 手动注入axe-core源码
直接导入axe-core包,将其源码传入AxeBuilder,避免依赖本地文件读取:
- 先安装axe-core:
npm install axe-core - 修改代码中的
AxeBuilder初始化逻辑
修改后的完整代码
import { chromium } from "playwright"; import { AxeBuilder } from "@axe-core/playwright"; import axeCore from 'axe-core'; import { NextRequest, NextResponse } from 'next/server'; // 强制使用Node.js运行时,支持文件系统和Playwright运行 export const runtime = 'nodejs'; export async function POST(req: NextRequest) { const browser = await chromium.launch(); const context = await browser.newContext(); const page = await context.newPage(); await page.goto("https://example.com"); // 传入axe-core的源码,绕过本地文件读取逻辑 const results = await new AxeBuilder({ page, axeSource: axeCore.source }).analyze(); await browser.close(); return NextResponse.json({ results }); }
关键说明
- 边缘运行时不支持Playwright:Playwright需要启动浏览器进程,而边缘环境限制了子进程创建,因此必须切换到Node.js运行时。
- 避免手动读取node_modules文件:新版本的axe-core不再直接暴露
axe.min.js文件在node_modules中,直接导入包并使用axeCore.source是官方推荐的正确方式。
内容的提问来源于stack exchange,提问作者m0t0rhektor
相关产品推荐
相关产品推荐

