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

Node.js中创建CosmosClient时出现无效URL错误

CosmosDB Node.js SDK 连接时触发无效URL错误问题

在Node.js环境中使用@azure/cosmos的CosmosClient连接CosmosDB时,触发了ERR_INVALID_URL错误。已确认密钥和连接字符串有效——同一套凭据在C#/.NET的Azure Functions项目中能正常连接数据库。尝试两种初始化方式(直接传入连接字符串、分别传入endpoint和密钥)均报错。

测试代码

const { CosmosClient } = require("@azure/cosmos");

const endPoint = "<obscured endpoint>";
const url = new URL(endPoint);
console.log(url.toJSON()); // 添加此代码测试URL,结果正常

const key = "<obscured key>";
const connectionString = "<obscured connection string that encodes the endpoint and key>";
const cosmosClient = new CosmosClient({ connectionString });

报错信息

Uncaught TypeError TypeError [ERR_INVALID_URL]: Invalid URL
    at __node_internal_captureLargerStackTrace (internal/errors:491:5)
    at NodeError (internal/errors:400:5)
    at onParseError (internal/url:565:9)
    at URL (internal/url:645:5)
    at checkURL (c:\Web3Scan\Web3Scan\node_modules\@azure\cosmos\src\utils\checkURL.ts:5:10)
    at CosmosClient (c:\Web3Scan\Web3Scan\node_modules\@azure\cosmos\src\CosmosClient.ts:68:22)
    at <anonymous> (c:\Web3Scan\Web3Scan\app.js:16:23)
    at Module._compile (internal/modules/cjs/loader:1218:14)
    at Module._extensions..js (internal/modules/cjs/loader:1272:10)
    at Module.load (internal/modules/cjs/loader:1081:32)
    at Module._load (internal/modules/cjs/loader:922:12)
    at executeUserEntryPoint (internal/modules/run_main:82:12)
    at <anonymous> (internal/main/run_main_module:23:47)

困惑点

查看SDK中的checkURL.ts代码,发现其URL校验逻辑和我自己测试用的完全一致,但SDK校验失败,自己测试却成功:

export function checkURL(testString: string): URL {
  return new URL(testString);  // 与我测试用的校验逻辑完全一致,但我的测试成功
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:42:34