发出 POST 请求时出现 Google Cloud Function CORS 错误

时间:2021-03-22 09:15:43

标签: node.js request google-cloud-functions cors preflight

我无法在 GCF 中启用 CORS,启用了 allUsers。这是我在 this post recommandations

之后的代码

我使用 fetch 和 JSON 作为主体进行 POST 调用。 我的服务器应该通过执行 reCaptcha 验证来处理请求。 然后根据 reCaptcha 分数做出回应。

问题是我什至无法发出请求,我的服务器返回状态 500。 以“mode : no-cors”发送时发送电子邮件。

exports.contactSendmail = (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');

  if (req.method === 'OPTIONS') {
    /* handle preflight OPTIONS request */

    res.set('Access-Control-Allow-Methods', 'GET, POST');
    res.set('Access-Control-Allow-Headers', 'Content-Type, Accept');

    // cache preflight response for 3600 sec
    res.set('Access-Control-Max-Age', '3600');

    return res.status(204);
  }

  const { message, token, email } = JSON.parse(req.body);
  console.log(message, token, email);

  // Load Node native HTTPS package
  const https = require('https');
  const sgMail = require('@sendgrid/mail');
  sgMail.setApiKey(process.env.SENDGRID_API_KEY);
  const recapatchaKeys = {
    secret: `myhiddensecretkey`,
    response: token,
  };
  const urlPath = `/recaptcha/api/siteverify?secret=${recapatchaKeys.secret}&response=${recapatchaKeys.response}`;
  const recaptchaOptions = {
    hostname: 'google.com',
    // port: 443,
    path: urlPath,
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': 0,
    },
  };
  const reqRecaptcha = https.request(recaptchaOptions, (recaptchaResponse) => {
    console.log(`reCaptcha statusCode: ${recaptchaResponse.statusCode}`);
    recaptchaResponse.on('data', (d) => {
      process.stdout.write(d);
      const recapatchaRes = JSON.parse(d);
      if (recapatchaRes.score > 0.7) {
        const msg = {
          to: process.env.CONTACT_EMAIL_RECIPIENT,
          from: email,
          subject: 'Nouveau contact',
          text: message,
          // html: "<strong>Its too simple to send mail</strong>"
        };
        //ES8
        (async () => {
          try {
            await sgMail.send(msg);
            res.status(200).send('Email sent');
            console.log('Email sent !');
          } catch (err) {
            console.error('Error with Sendgrid' + err.toString());
          }
        })();
      } else {
        res.status(403).send('Forbidden to send Email');
        console.log('Forbidden to send Email');
      }
    });
  });
  reqRecaptcha.write('');
  reqRecaptcha.end();
};

这是我的前台电话

const response = await fetch(process.env.CONTACT_SENDMAIL_URL, {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(emailBody),
});

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

正如评论中提到的,您没有在那里处理任何身份验证。 Documentation 声明:

<块引用>

您可以使用 --allow-unauthenticated 标志部署它,也可以使用控制台将 Cloud Functions Invoker 角色授予 allUsers。然后在函数代码中处理CORS和认证。

为了处理最终用户的身份验证,您可以在您的代码中按照 documentation 的另一部分中的说明进行操作,该部分非常详细。

相关问题