Azure通信服务邮件Node.js:如何正确格式化连接字符串?
问题修复方案
核心错误原因
你完全搞错了CONNECTION_STRING_REGEX的用途——它应该是匹配标准Azure连接字符串格式的正则表达式,而不是直接把你的端点和密钥硬编码进去。当前写法导致正则完全无法解析有效字符串,所以才会一直报端点或密钥未定义。
Azure通信服务的标准连接字符串格式是:
Endpoint=https://<你的资源名称>.communication.azure.com/;AccessKey=<你的访问密钥>
修正后的代码
把正则表达式改成正确匹配上述格式的写法,同时修复console.log的语法错误:
// Copyright (c) Microsoft Corporation. const CONNECTION_STRING_REGEX = /Endpoint=(https:\/\/[^;]+);AccessKey=([^;]+)/i; const tryParseConnectionString = (s) => { const match = s.match(CONNECTION_STRING_REGEX); if (match?.[1] && match[2]) { return { endpoint: match[1], credential: new coreAuth.AzureKeyCredential(match[2]) }; } return undefined; }; /** Returns an EndpointCredential to easily access properties of the connection string. @hidden @param connectionString - The connection string to parse @returns Object to access the endpoint and the credentials */ const parseConnectionString = (connectionString) => { console.log("ParseConnectionString"); const parsedConnectionString = tryParseConnectionString(connectionString); if (parsedConnectionString) { return parsedConnectionString; } else { throw new Error(`Invalid connection string ${connectionString}`); } };
使用说明
- 从Azure门户获取你的通信服务资源的完整连接字符串(不是分开的端点和密钥)。
- 在调用
parseConnectionString时传入这个完整的连接字符串:
const connectionString = "Endpoint=https://emailtesting.unitedstates.communication.azure.com/;AccessKey=xxxxxxxxx"; const { endpoint, credential } = parseConnectionString(connectionString); // 之后用endpoint和credential初始化邮件客户端
额外注意事项
- 确保你已经正确导入了
@azure/core-auth包,否则AzureKeyCredential会报错。 - 不要手动拆分端点和密钥,让正则表达式自动解析标准连接字符串即可。
内容的提问来源于stack exchange,提问作者coderChris
相关产品推荐
相关产品推荐

