You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright调用API报apiRequestContext.fetch: Invalid URL错误求助

解决Playwright中page.request.get报apiRequestContext.fetch: Invalid URL错误

核心原因:baseURL自动拼接干扰

你的配置中use字段设置了baseURL,而page.request会默认将baseURL与你传入的请求URL拼接。如果baseURL是项目自身的域名(比如http://localhost:4200),拼接后会生成类似http://localhost:4200https://api.thecatapi.com/v1/images/0XYvRd7oD的无效URL,这就是报错的根本原因。

两种可行解决方案

方案1:使用独立的API请求上下文

创建不继承页面baseURL的独立请求上下文,专门用于外部API调用:

import { test } from '@playwright/test';

test('调用外部公共API', async ({ playwright }) => {
  // 创建独立的API请求上下文
  const apiContext = await playwright.request.newContext();
  // 发起GET请求
  const res = await apiContext.get('https://api.thecatapi.com/v1/images/0XYvRd7oD');
  // 打印响应内容(res.body是异步方法,需调用json/text获取实际内容)
  console.log(await res.json());
  // 用完销毁上下文
  await apiContext.dispose();
});

方案2:调用page.request时覆盖baseURL

如果想继续使用page.request,可以在请求时显式将baseURL设为undefined,避免自动拼接:

page.request.get('https://api.thecatapi.com/v1/images/0XYvRd7oD', { baseURL: undefined })
  .then(res => res.json().then(data => console.log(data)));

额外验证点

  • 确认baseURL变量的值:如果它不是空字符串,就会触发自动拼接逻辑,导致外部API的URL失效。
  • 检查请求URL是否有拼写错误(你提供的URL在浏览器正常,此点可排除)。

内容的提问来源于stack exchange,提问作者Bryan Alcorn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 15:28:20