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

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}`);
  }
};

使用说明

  1. 从Azure门户获取你的通信服务资源的完整连接字符串(不是分开的端点和密钥)。
  2. 在调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 23:52:51