【发布时间】:2021-10-16 20:34:55
【问题描述】:
目前正在尝试直接从我的 web 应用程序中使用 google 云功能,该功能会进行 mongodb 查询并将数据返回到客户端浏览器。我收到以下错误。
i functions: Beginning execution of "us-central1-fullName"
> {"verifications":{"app":"MISSING","auth":"MISSING"},"logging.googleapis.com/labels":{"firebase-log-type":"callable-request-verification"},"severity":"INFO","message":"Callable request verification passed"}
> {"severity":"ERROR","message":"Unhandled error TypeError: Cannot read property 'origin' of undefined\n at C:\\Users\\myalt\\s\\functions\\node_modules\\cors\\lib\\index.js:219:40\n at optionsCallback (C:\\Users\\myalt\\s\\functions\\node_modules\\cors\\lib\\index.js:199:9)\n at corsMiddleware (C:\\Users\\myalt\\s\\functions\\node_modules\\cors\\lib\\index.js:204:7)\n at C:\\Users\\myalt\\s\\functions\\index.js:6:5\n at newHandler (C:\\Users\\myalt\\AppData\\Roaming\\npm\\node_modules\\firebase-tools\\lib\\emulator\\functionsEmulatorRuntime.js:296:16)\n at C:\\Users\\myalt\\s\\functions\\node_modules\\firebase-functions\\lib\\common\\providers\\https.js:322:32\n at processTicksAndRejections (internal/process/task_queues.js:93:5)"}
i functions: Finished "us-central1-fullName" in ~1s
我最初收到此错误:
Access to fetch at 'https://us-central1--8955f.cloudfunctions.net/fullName' from origin 'https://-8955f.web.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
但是,我通过添加解决了这个问题
const cors = require('cors')({ Origin: true });
exports.fullName = functions.region('us-central1').https.onCall((req, res) => {
cors(req, res, () => {
// my function
}
我不完全确定为什么会发生此起源错误。任何帮助将不胜感激。
const cors = require('cors')({ Origin: true });
exports.fullName = functions.region('us-central1').https.onCall((req, res) => {
cors(req, res, () => {
return new Promise((resolve, reject) => { // ???? return a promise, so Cloud Functions knows to wait
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://:/?readPreference=primary&appname=MongoDB%20Compass&ssl=false";
MongoClient.connect(url, function (err, db) {
console.log('Connected to database.')
if (err) throw err;
var dbo = db.db("discord_pandemic");
dbo.collection("ArrayStats").find().toArray(function (err, result) {
if (err) throw err;
const totalInfections = result[0].total_infections
const totalUsers = result[0].total_users
const totalCommands = result[0].total_commands
const totalLiveInfections = result[0].total_live_infections
const totalLiveInfectedChannels = result[0].total_live_infected_channels
const data = {
totalInfections: totalInfections,
totalUsers: totalUsers,
totalCommands: totalCommands,
totalLiveInfections: totalLiveInfections,
totalLiveInfectedChannels: totalLiveInfectedChannels
}
resolve(data); // ???? resolve the promise with the data for the user
});
});
});
})
})
【问题讨论】:
标签: node.js firebase google-cloud-platform