【发布时间】:2021-06-18 22:17:16
【问题描述】:
我无法在 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),
});
任何帮助将不胜感激
【问题讨论】:
-
您没有在其中处理任何身份验证,Docs 声明如果启用
allUsers,您应该在函数中处理身份验证以及 CORS(您正在执行的操作)以使其工作。或者,您可以尝试使用--allow-unauthenticated部署它,这可能在您的项目中吗? -
我已经使用“允许未经身份验证”(=> prnt.sc/10ubr02) 部署了我的函数。实际上,文档声明“然后在函数代码中处理 CORS 和身份验证”,但是我如何在代码中处理身份验证?
-
您可以按照here 的说明进行操作。
标签: node.js request google-cloud-functions cors preflight