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

调用Google Cloud Function遇CORS错误,Postman正常站点调用失败

解决思路

1. 单独处理OPTIONS预请求

浏览器发起跨域POST请求前,会自动发送OPTIONS预请求验证权限。你的代码虽设置了CORS头,但未对OPTIONS请求做单独处理,导致预请求响应不符合规范。修改代码,在开头优先拦截OPTIONS请求:

const sgMail = require('@sendgrid/mail');
exports.sendEmail = async (req, res) => {
    // 直接响应OPTIONS预请求
    if (req.method === 'OPTIONS') {
        res.set('Access-Control-Allow-Origin', '*');
        res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.set('Access-Control-Allow-Headers', 'Content-Type');
        return res.status(204).send('');
    }

    // 建议用环境变量存储密钥,避免硬编码泄露
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    
    res.set('Access-Control-Allow-Origin', '*');
    res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
    res.set('Access-Control-Allow-Headers', 'Content-Type');

    const msg = {
        to: 'xxxxxxxxxxxx',
        from: 'xxxxxxxxxxxxxxxx',
        subject: req.body.subject,
        text: `${req.body.message}
                  
        ${req.body.email}
        ${req.body.phone}`,
    };
    try {
        await sgMail.send(msg);
        res.status(200).send('Email sent successfully');
    } catch (error) {
        console.error(error);
        if (error.response) {
            console.error(error.response.body);
        }
        res.status(500).send('Error sending email');
    }
};

2. 通过Google Cloud控制台配置CORS(替代代码处理)

可以直接在GCP控制台为云函数配置CORS规则,无需在代码中手动设置头:

  • 进入云函数详情页,点击「编辑」→「运行时、构建、连接设置」→「连接」→「CORS」
  • 添加允许的来源(如你的测试站点域名,或*)、允许的方法(POST, OPTIONS)、允许的头(Content-Type)
  • 保存后重新部署函数,浏览器预请求会由GCP网关直接处理

3. 优化敏感信息存储

将SendGrid API密钥从代码中移除,改用云函数环境变量:

  • 在云函数控制台「编辑」→「运行时、构建、连接设置」→「运行时变量」中添加SENDGRID_API_KEY,值为你的密钥
  • 代码中通过process.env.SENDGRID_API_KEY调用,避免密钥泄露风险

内容的提问来源于stack exchange,提问作者Yesid Bejarano Camacho

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 21:15:18