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

React应用集成Azure Communication Services发邮件遇CORS错误求解决

解决React前端调用Azure Communication Services邮件API的CORS问题

直接在React前端调用Azure Communication Services的邮件发送接口触发CORS错误,核心原因是这类API设计为后端服务端调用,而非浏览器端:一方面调用时需要的Azure密钥属于敏感信息,不能暴露在前端代码中;另一方面Azure也没有为这类接口配置允许前端域名的CORS规则。

以下是两种可行的解决方式:

方案1:搭建后端代理服务(推荐)

自己实现一个简单的后端接口,前端调用该接口,再由后端去调用Azure的邮件API,既绕开CORS问题,又能保护敏感信息不泄露。

示例:用Node.js+Express实现代理服务

  1. 初始化并编写后端代码:
const express = require('express');
const { EmailClient } = require("@azure/communication-email");
const cors = require('cors');
const app = express();

// 开发环境可临时允许localhost:3000,生产环境需指定具体域名
app.use(cors({ origin: 'http://localhost:3000' }));
app.use(express.json());

// 从环境变量读取Azure连接字符串,禁止硬编码!
const connectionString = process.env.AZURE_COMMUNICATION_CONNECTION_STRING;
const emailClient = new EmailClient(connectionString);

// 自定义邮件发送接口
app.post('/api/send-email', async (req, res) => {
  try {
    const { sender, recipients, subject, content } = req.body;
    const message = {
      senderAddress: sender,
      recipients,
      content: {
        subject,
        plainText: content.plainText,
        html: content.html
      }
    };
    const sendResult = await emailClient.send(message);
    res.status(200).json(sendResult);
  } catch (err) {
    console.error(err);
    res.status(500).json({ msg: '邮件发送失败' });
  }
});

app.listen(5000, () => {
  console.log('代理服务运行在 http://localhost:5000');
});
  1. React前端调用代理接口:
const sendEmail = async () => {
  try {
    const res = await fetch('http://localhost:5000/api/send-email', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        sender: '你的发件邮箱@配置的域名.com',
        recipients: { to: [{ address: '收件人邮箱@example.com' }] },
        subject: '测试邮件',
        content: {
          plainText: '这是一封测试邮件',
          html: '<h1>测试邮件</h1><p>来自React前端的邮件</p>'
        }
      })
    });
    const data = await res.json();
    console.log('发送成功', data);
  } catch (err) {
    console.error('发送失败', err);
  }
};

方案2:用Azure Functions做无服务器代理

如果不想维护自己的后端,可以用Azure Functions创建一个无服务器中间层:

  • 创建HTTP触发的Azure Function,在函数内部调用Azure邮件API
  • 在Azure Functions控制台配置CORS,允许你的React前端域名(如http://localhost:3000)
  • 前端直接调用该Function的URL即可

关键注意事项

  • 无论哪种方案,绝对不能将Azure连接字符串或密钥写入前端代码,避免敏感信息泄露
  • 生产环境中,CORS规则要严格限制允许的域名,不要用通配符*
  • 确保你的Azure Communication Services资源已正确配置邮件发送的域名和权限

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:45:33