我有以下代码可以验证谷歌验证码 v3在我的 Firebase 函数中导致CORS issue:
const functions = require('firebase-functions');
const nodemailer = require("nodemailer");
const express = require("express");
const cors = require("cors");
const request = require('request');
const serverApi = express();
api.use(cors({ origin: true }));
function verifyCaptcha(token, returnData) {
// Put your secret key here.
var secretKey = functions.config().recaptcha.secretkey;
var verificationUrl = "https://www.google.com/recaptcha/api/siteverify?secret=" + secretKey + "&response=" + token;
// Note here: External network call to google.com
request(verificationUrl, function (error, response, body) {
body = JSON.parse(body);
// Success will be true or false depending upon captcha validation.
if (!body.success) {
body['status'] = false;
body['errSource'] = "recaptcha";
body['message'] = "Failed to pass captcha verification.";
} else {
body['status'] = true;
body['message'] = "Successfully passed captcha verification!";
};
console.log(`Google returns: ${JSON.stringify(body)}`);
returnData(body);
});
};
api.post("/api/service-name", (req, res) => {
if (!req.body['g-recaptcha-response']) {
return res.send({ "status": false, "errSource": "recaptcha", "message": "Client-side reCAPTCHA token not found." });
};
const recaptchaToken = req.body['g-recaptcha-response'];
verifyCaptcha(recaptchaToken, function (result) {
if (result.status == false) {
return res.send(result);
};
// My business logics here.
});
});
exports.api = functions.https.onRequest(api);
我注意到在我的 Firebase 函数中删除 reCAPTCHA v3 验证请求后,我的本地主机不再需要调用 CORS 问题"/api/service-name"
using $.ajax()
。这是因为下面的 Firebase 函数日志让我想起了“无法访问外部网络”:
Billing account not configured. External network is not accessible and quotas are severely limited.
Configure billing account to remove these restrictions
我的问题是:有没有办法让我的服务器端 reCAPTCHA 验证正常工作,而不会导致此 CORS 问题,这可以通过“未配置计费帐户”来防止?谢谢!
UPDATE:
抓住之后request()
进行验证时出错,我收到以下错误:
{errno: "EAI_AGAIN", code: "EAI_AGAIN", syscall: "getaddrinfo", hostname: "www.google.com", host: "www.google.com", …}
另外,处理此错误后,不再有 CORS 问题,但 reCAPTCHA 仍然无法验证。知道是什么原因造成的吗?再次感谢!